<template>
  <div class="reports-page">

    <!-- 报表类型选择 -->
    <el-card class="report-type-card" style="margin-bottom: 20px;">
      <template #header>
        <span>📊 报表类型</span>
      </template>
      <el-radio-group v-model="reportType" @change="handleReportTypeChange" size="large">
        <el-radio-button label="detail">PPH记录详情</el-radio-button>
        <el-radio-button label="pph_summary">PPH汇总表</el-radio-button>
        <el-radio-button label="abnormal_summary">异常汇总表</el-radio-button>
        <el-radio-button label="abnormal_weekly">异常汇总（周）</el-radio-button>
        <el-radio-button label="efficiency_analysis">达标率分析</el-radio-button>
      </el-radio-group>

    </el-card>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <!-- 异常汇总（周）专用筛选条件 -->
      <div v-if="reportType === 'abnormal_weekly'" class="weekly-filters" style="margin-bottom: 20px;">
        <el-form label-width="80px">
          <!-- 第一行：快捷时间 + 统计粒度 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="快捷时间">
                <el-radio-group v-model="weeklyPreset" size="default">
                  <el-radio-button label="this_week">本周</el-radio-button>
                  <el-radio-button label="last_week">上周</el-radio-button>
                  <el-radio-button label="this_month">本月</el-radio-button>
                  <el-radio-button label="last_month">上月</el-radio-button>
                  <el-radio-button label="this_year">本年</el-radio-button>
                  <el-radio-button label="last_year">上年</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="统计粒度">
                <el-select v-model="weeklyGranularity" style="width: 100%">
                  <el-option label="按周" value="week" />
                  <el-option label="按月" value="month" />
                  <el-option label="按年" value="year" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：起止年/月、异常类别、查询/重置/导出 -->
          <el-row :gutter="20" style="margin-top: 10px;">
            <el-col v-if="showYearMonthControls" :span="4">
              <el-form-item label="起始年份">
                <el-select v-model="weeklyStartYear" placeholder="起始年份" style="width: 100%">
                  <el-option v-for="year in getYearOptions()" :key="year" :label="year + '年'" :value="year" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="showYearMonthControls" :span="4">
              <el-form-item label="结束年份">
                <el-select v-model="weeklyEndYear" placeholder="结束年份" style="width: 100%">
                  <el-option v-for="year in getYearOptions()" :key="year" :label="year + '年'" :value="year" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="showYearMonthControls" :span="4">
              <el-form-item label="起始月份">
                <el-select v-model="weeklyStartMonth" placeholder="起始月份" style="width: 100%">
                  <el-option v-for="month in 12" :key="month" :label="month + '月'" :value="month" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="showYearMonthControls" :span="4">
              <el-form-item label="结束月份">
                <el-select v-model="weeklyEndMonth" placeholder="结束月份" style="width: 100%">
                  <el-option v-for="month in 12" :key="month" :label="month + '月'" :value="month" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="异常类别">
                <el-select v-model="weeklyAbnormalityCategory" placeholder="全部类别" clearable style="width: 100%">
                  <el-option v-for="category in abnormalityCategories" :key="category.id" :label="category.category_name" :value="category.category_name" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="text-align: right;">
              <el-space>
                <el-button type="primary" @click="loadAbnormalWeeklyData" :loading="loading" :icon="Search">查询</el-button>
                <el-button @click="resetWeeklyFilters" :icon="Refresh">重置</el-button>
                <el-button @click="exportWeeklyReport" :icon="Download">导出</el-button>
              </el-space>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- PPH记录详情筛选条件 -->
      <div v-else-if="reportType === 'detail'" class="search-container">
        <el-form :model="filters" label-width="100px" class="search-form">
          <!-- 快捷时间：单独一行（置于日期范围上方） -->
          <div class="form-row">
            <el-form-item label="快捷时间">
              <el-radio-group v-model="detailPreset" @change="applyDetailPreset">
                <el-radio-button label="this_week">本周</el-radio-button>
                <el-radio-button label="last_week">上周</el-radio-button>
                <el-radio-button label="this_month">本月</el-radio-button>
                <el-radio-button label="last_month">上月</el-radio-button>
                <el-radio-button label="this_year">本年</el-radio-button>
                <el-radio-button label="last_year">上年</el-radio-button>
                <el-radio-button label="last_7_days">近7天</el-radio-button>
                <el-radio-button label="last_30_days">近30天</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 第一行：日期、生产线、订单号、物料编码 -->
          <div class="form-row">
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleDateRangeChange"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="生产线">
              <el-select v-model="filters.line_names" multiple collapse-tags filterable placeholder="选择生产线(可多选)" clearable style="width: 360px">
                <el-option
                  v-for="line in lines"
                  :key="line.line_name"
                  :label="line.line_name"
                  :value="line.line_name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="filters.order_number" v-trim-input placeholder="输入订单号" clearable style="width: 180px" />
            </el-form-item>
            <el-form-item label="物料编码">
              <el-input v-model="filters.material_code" v-trim-input placeholder="输入物料编码" clearable style="width: 180px" />
            </el-form-item>
          </div>

          <!-- 第二行：物料名称、达成率条件和操作按钮 -->
          <div class="form-row form-row-with-buttons">
            <div class="form-fields">
              <el-form-item label="物料名称">
                <el-input v-model="filters.product_name" v-trim-input placeholder="输入物料名称" clearable style="width: 200px" />
              </el-form-item>
              <el-form-item label="达成率">
                <div style="display: flex; align-items: center; gap: 8px;">
                  <el-select v-model="filters.efficiency_operator" placeholder="条件" style="width: 80px">
                    <el-option label=">" value="gt" />
                    <el-option label=">=" value="gte" />
                    <el-option label="=" value="eq" />
                    <el-option label="<=" value="lte" />
                    <el-option label="<" value="lt" />
                  </el-select>
                  <el-input-number
                    v-model="filters.efficiency_value"
                    placeholder=""
                    :min="0"
                    :max="1000"
                    style="width: 120px"
                    controls-position="right"
                  />
                  <span style="color: #606266;">%</span>
                </div>
              </el-form-item>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-buttons">
              <el-button type="primary" @click="loadReportData" :icon="Search" class="action-btn">查询</el-button>
              <el-button @click="resetFilters" :icon="Refresh" class="action-btn">重置</el-button>
              <el-button @click="exportReport" :icon="Download" class="action-btn">导出报表</el-button>
            </div>
          </div>
        </el-form>
      </div>

      <!-- PPH汇总表筛选条件 -->
      <div v-else-if="reportType === 'pph_summary'" class="search-container">
        <el-form :model="pphSummaryFilters" label-width="100px" class="search-form">
          <!-- 快捷时间：PPH汇总（日期范围上方） -->
          <div class="form-row">
            <el-form-item label="快捷时间">
              <el-radio-group v-model="pphSummaryPreset" @change="applyPphSummaryPreset">
                <el-radio-button label="this_week">本周</el-radio-button>
                <el-radio-button label="last_week">上周</el-radio-button>
                <el-radio-button label="this_month">本月</el-radio-button>
                <el-radio-button label="last_month">上月</el-radio-button>
                <el-radio-button label="this_year">本年</el-radio-button>
                <el-radio-button label="last_year">上年</el-radio-button>
                <el-radio-button label="last_7_days">近7天</el-radio-button>
                <el-radio-button label="last_30_days">近30天</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 第一行：日期、生产线、订单号、物料编码 -->
          <div class="form-row">
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="pphSummaryDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="生产线">
              <el-select v-model="pphSummaryFilters.line_names" multiple collapse-tags filterable placeholder="选择生产线(可多选)" clearable style="width: 360px">
                <el-option
                  v-for="line in lines"
                  :key="line.line_name"
                  :label="line.line_name"
                  :value="line.line_name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="pphSummaryFilters.order_number" v-trim-input placeholder="输入订单号" clearable style="width: 180px" />
            </el-form-item>
            <el-form-item label="物料编码">
              <el-input v-model="pphSummaryFilters.material_code" v-trim-input placeholder="输入物料编码" clearable style="width: 180px" />
            </el-form-item>
          </div>

          <!-- 第二行：物料名称和操作按钮 -->
          <div class="form-row form-row-with-buttons">

            <div class="form-fields">
              <el-form-item label="物料名称">
                <el-input v-model="pphSummaryFilters.product_name" v-trim-input placeholder="输入物料名称" clearable style="width: 200px" />
              </el-form-item>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-buttons">
              <el-button type="primary" @click="loadPPHSummaryData" :icon="Search" class="action-btn">查询</el-button>
              <el-button @click="resetPPHSummaryFilters" :icon="Refresh" class="action-btn">重置</el-button>
              <el-button @click="exportPPHSummaryReport" :icon="Download" class="action-btn">导出报表</el-button>
            </div>
          </div>
        </el-form>
      </div>

      <!-- 异常汇总表筛选条件 -->
      <div v-else-if="reportType === 'abnormal_summary'" class="search-container">
        <el-form :model="abnormalSummaryFilters" label-width="100px" class="search-form">
          <!-- 快捷时间（异常汇总） -->
          <div class="form-row">
            <el-form-item label="快捷时间">
              <el-radio-group v-model="abnormalSummaryPreset" @change="applyAbnormalSummaryPreset">
                <el-radio-button label="this_week">本周</el-radio-button>
                <el-radio-button label="last_week">上周</el-radio-button>
                <el-radio-button label="this_month">本月</el-radio-button>
                <el-radio-button label="last_month">上月</el-radio-button>
                <el-radio-button label="this_year">本年</el-radio-button>
                <el-radio-button label="last_year">上年</el-radio-button>
                <el-radio-button label="last_7_days">近7天</el-radio-button>
                <el-radio-button label="last_30_days">近30天</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>
          <!-- 第一行：日期、生产线、订单号、物料编码 -->
          <div class="form-row">
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="abnormalSummaryDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="生产线">
              <el-select v-model="abnormalSummaryFilters.line_name" placeholder="选择生产线" clearable style="width: 150px">
                <el-option
                  v-for="line in lines"
                  :key="line.line_name"
                  :label="line.line_name"
                  :value="line.line_name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="订单号">
              <el-input v-model="abnormalSummaryFilters.order_number" v-trim-input placeholder="输入订单号" clearable style="width: 180px" />
            </el-form-item>
            <el-form-item label="物料编码">
              <el-input v-model="abnormalSummaryFilters.material_code" v-trim-input placeholder="输入物料编码" clearable style="width: 180px" />
            </el-form-item>
          </div>

          <!-- 第二行：物料名称、异常类别、异常关闭和操作按钮 -->
          <div class="form-row form-row-with-buttons">
            <div class="form-fields">
              <el-form-item label="物料名称">
                <el-input v-model="abnormalSummaryFilters.product_name" v-trim-input placeholder="输入物料名称" clearable style="width: 200px" />
              </el-form-item>
              <el-form-item label="异常类别">
                <el-select v-model="abnormalSummaryFilters.abnormality_category" placeholder="选择异常类别" clearable style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="category in abnormalityCategories"
                    :key="category.id"
                    :label="category.category_name"
                    :value="category.category_name"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="异常关闭">
                <el-select v-model="abnormalSummaryFilters.abnormality_closed" placeholder="选择状态" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="是" value="是" />
                  <el-option label="否" value="否" />
                </el-select>
              </el-form-item>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-buttons">
              <el-button type="primary" @click="loadAbnormalSummaryData" :icon="Search" class="action-btn">查询</el-button>
              <el-button @click="resetAbnormalSummaryFilters" :icon="Refresh" class="action-btn">重置</el-button>
              <el-button @click="exportAbnormalSummaryReport" :icon="Download" class="action-btn">导出报表</el-button>
            </div>
          </div>
          </el-form>
        </div>

      <!-- 达标率分析筛选条件 -->
      <div v-else-if="reportType === 'efficiency_analysis'" class="search-container">
        <el-form label-width="90px" class="search-form">
          <!-- 第一行：快捷时间 + 粒度 + 维度 -->
          <div class="form-row">
            <el-form-item label="快捷时间">
              <el-radio-group v-model="effPreset" @change="applyEffPreset">
                <el-radio-button label="this_week">本周</el-radio-button>
                <el-radio-button label="last_week">上周</el-radio-button>
                <el-radio-button label="this_month">本月</el-radio-button>
                <el-radio-button label="last_month">上月</el-radio-button>
                <el-radio-button label="this_year">本年</el-radio-button>
                <el-radio-button label="last_year">上年</el-radio-button>
                <el-radio-button label="last_7_days">近7天</el-radio-button>
                <el-radio-button label="last_30_days">近30天</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="粒度">
              <el-select v-model="effGranularity" style="width: 140px">
                <el-option label="按周" value="week" />
                <el-option label="按月" value="month" />
                <el-option label="按年" value="year" />
              </el-select>
            </el-form-item>
            <el-form-item label="维度">
              <el-select v-model="effDimension" style="width: 140px">
                <el-option label="总体" value="overall" />
                <el-option label="按生产线" value="line" />
              </el-select>
              <template v-if="effDimension==='line'">
                <el-select v-model="effSelectedLines" multiple collapse-tags filterable placeholder="选择生产线(默认全选)" style="width: 420px; margin-left: 12px;">
                  <el-option v-for="ln in lines" :key="ln.line_name" :label="ln.line_name" :value="ln.line_name" />
                </el-select>
                <el-select v-model="effRankingMode" style="width: 140px; margin-left: 8px;">
                  <el-option label="TopN" value="top" />
                  <el-option label="BottomN" value="bottom" />
                </el-select>
                <el-input-number v-model="effRankingN" :min="1" :max="20" :step="1" style="width: 120px; margin-left: 8px" />
              </template>
            </el-form-item>
          </div>

          <!-- 第二行：起止年/月（按需显示） + 阈值 + 操作按钮 -->
          <div class="form-row form-row-with-buttons" style="margin-top: 8px;">
            <div class="form-fields">
              <template v-if="effGranularity !== 'week'">
                <el-form-item label="起始年份">
                  <el-select v-model="effStartYear" style="width: 120px">
                    <el-option v-for="y in getYearOptions()" :key="y" :label="y" :value="y" />
                  </el-select>
                </el-form-item>
                <el-form-item label="结束年份">
                  <el-select v-model="effEndYear" style="width: 120px">
                    <el-option v-for="y in getYearOptions()" :key="y" :label="y" :value="y" />
                  </el-select>
                </el-form-item>
                <el-form-item label="起始月份">
                  <el-select v-model="effStartMonth" style="width: 120px">
                    <el-option v-for="m in 12" :key="m" :label="m" :value="m" />
                  </el-select>
                </el-form-item>
                <el-form-item label="结束月份">
                  <el-select v-model="effEndMonth" style="width: 120px">
                    <el-option v-for="m in 12" :key="m" :label="m" :value="m" />
                  </el-select>
                </el-form-item>
              </template>

            <div class="form-row" style="margin-top:8px">
              <el-form-item label="口径">
                <el-radio-group v-model="effMetric">
                  <el-radio-button label="pass_rate">达标率(阈值)</el-radio-button>
                  <el-radio-button label="avg_efficiency">平均达成率(无阈值)</el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="图表">
                <el-radio-group v-model="effChartType">
                  <el-radio-button label="line">折线</el-radio-button>
                  <el-radio-button label="bar">柱状</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </div>


              <el-form-item label="阈值(%)">
                <el-input-number v-model="effThreshold" :min="50" :max="150" :precision="0" :step="1" style="width: 140px" />
              </el-form-item>
            </div>

            <div class="action-buttons">
              <el-button type="primary" :icon="Search" @click="loadEfficiencyAnalysis">查询</el-button>
              <el-button :icon="Refresh" @click="resetEfficiencyFilters">重置</el-button>
              <el-button :icon="Download" @click="exportEfficiencyAnalysis">导出</el-button>
            </div>
          </div>
        </el-form>

        <!-- 达标率分析图表与表格 -->
        <el-card class="data-table" style="margin-top: 16px;">
          <template #header>
            <div style="display:flex;justify-content:space-between;align-items:center;">
              <span>达标率分析（{{ effDimension === 'line' ? '按生产线' : '总体' }}｜{{ effGranLabel }}）</span>
              <span style="font-size:12px;color:#909399;">覆盖率均值：{{ (effStats.coverage ?? 0).toFixed(1) }}%</span>
            </div>
          </template>
          <div id="eff-chart" style="width:100%;height:360px;"></div>
          <el-table :data="effTableRows" border stripe style="margin-top: 12px;">
            <el-table-column prop="period" label="周期" min-width="120" />
            <el-table-column v-if="effDimension==='line'" prop="line_name" label="生产线" min-width="120" />
            <el-table-column prop="total_groups" label="总分组" min-width="100" align="right" />
            <el-table-column prop="covered_groups" label="有效分组(有目标)" min-width="140" align="right" />
            <el-table-column prop="coverage" label="覆盖率%" min-width="100" align="right" />
            <el-table-column prop="pass_records" label="达标分组数" min-width="120" align="right" />
            <el-table-column v-if="effMetric==='pass_rate'" prop="pass_rate" label="达标率%" min-width="100" align="right" />
            <el-table-column v-else prop="avg_efficiency" label="平均达成率%" min-width="120" align="right" />
          </el-table>
        </el-card>
      </div>
    </el-card>

    <!-- 统计卡片（按报表类型切换） -->
    <!-- PPH 相关统计卡片 -->
    <el-row v-if="reportType === 'detail' || reportType === 'pph_summary'" :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="总记录数" :value="statistics.totalRecords" suffix="条" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="平均PPH" :value="statistics.averagePPH" suffix="件/人·时" :precision="2" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="平均达成率" :value="statistics.averageEfficiency" suffix="%" :precision="2" :value-style="{ color: statistics.averageEfficiency >= 100 ? '#67c23a' : '#f56c6c' }" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="达标率" :value="statistics.achievementRate" suffix="%" :precision="2" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 异常汇总统计卡片 -->
    <el-row v-else-if="reportType === 'abnormal_summary' || reportType === 'abnormal_weekly'" :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="异常总次数" :value="statistics.totalAbnormalRecords" suffix="条" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="异常类别数" :value="statistics.abnormalCategoriesCount" suffix="类" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="已关闭异常" :value="statistics.closedCount" suffix="条" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="未关闭异常" :value="statistics.unclosedCount" suffix="条" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="data-table">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>{{ getTableTitle() }}</span>
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-alert
              v-if="reportType === 'detail'"
              title="字段排序请在配置对话框中进行"
              type="info"
              :closable="false"
              :show-icon="false"
              style="padding: 4px 8px; font-size: 12px; margin: 0;"
            />
            <el-button
              v-if="reportType === 'detail'"
              size="small"
              @click="showFieldConfig"
              type="primary"
            >
              配置显示字段
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="tableRef"
        :data="getCurrentTableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :row-style="{ height: '60px' }"
        :cell-style="{ padding: '12px 8px' }"
        height="600"
        :header-cell-style="{
          position: 'sticky',
          top: 0,
          backgroundColor: '#f8f9fa',
          zIndex: 10
        }"
        @sort-change="handleSortChange"
      >
        <!-- PPH汇总表列 -->
        <template v-if="reportType === 'pph_summary'">
          <el-table-column prop="record_date" label="记录日期" min-width="120" sortable />
          <el-table-column prop="line_name" label="生产线" min-width="120" />
          <el-table-column prop="order_number" label="订单号" min-width="140" />
          <el-table-column prop="material_code" label="物料编码" min-width="140" />
          <el-table-column prop="product_name" label="产品名称" min-width="160" />
          <el-table-column prop="total_quantity" label="完成数量" min-width="120" align="right">
            <template #default="{ row }">
              {{ Math.round(row.total_quantity || 0) }}
            </template>
          </el-table-column>
          <el-table-column prop="avg_people" label="平均人数" min-width="120" align="right">
            <template #default="{ row }">
              {{ (row.avg_people || 0).toFixed(1) }}
            </template>
          </el-table-column>
          <el-table-column prop="total_minutes" label="净工作时间(分)" min-width="140" align="right">
            <template #default="{ row }">
              {{ Math.round(row.total_minutes || 0) }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_pph" label="实际PPH" min-width="120" align="right">
            <template #default="{ row }">
              {{ (row.actual_pph || 0).toFixed(1) }}
            </template>
          </el-table-column>
          <el-table-column prop="average_pph" label="平均PPH" min-width="120" align="right">
            <template #default="{ row }">
              {{ row.average_pph ? row.average_pph.toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="target_pph" label="目标PPH" min-width="120" align="right">
            <template #default="{ row }">
              {{ row.target_pph ? row.target_pph.toFixed(2) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="estimate_pph" label="预估PPH" min-width="120" align="right">
            <template #default="{ row }">
              {{ row.estimate_pph ? row.estimate_pph.toFixed(1) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="efficiency_rate" label="达成率(%)" min-width="120" align="right">
            <template #default="{ row }">
              <span v-if="row.efficiency_rate !== null && row.efficiency_rate !== undefined"
                    :style="{ color: (row.efficiency_rate || 0) >= 100 ? '#67C23A' : '#F56C6C' }">
                {{ row.efficiency_rate.toFixed(1) }}%
              </span>
              <span v-else style="color: #909399;">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="is_main_product" label="主打产品" min-width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getMainProductValue(row.is_main_product) ? 'success' : 'info'" size="small">
                {{ getMainProductValue(row.is_main_product) ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="production_type" label="生产类型" min-width="100" />
        </template>

        <!-- 异常汇总表列 -->
        <template v-else-if="reportType === 'abnormal_summary'">
          <el-table-column prop="record_date" label="记录日期" min-width="120" sortable />
          <el-table-column prop="line_name" label="生产线" min-width="120" />
          <el-table-column prop="order_number" label="订单号" min-width="140" />
          <el-table-column prop="material_code" label="物料编码" min-width="140" />
          <el-table-column prop="product_name" label="产品名称" min-width="160" />
          <!-- 异常类别 - 可编辑 -->
          <el-table-column prop="abnormality_category" label="异常类别" min-width="160">
            <template #default="{ row, $index }">
              <div v-if="!isRowEditing(row)" @dblclick="startEdit(row)">
                {{ row.abnormality_category || '无' }}
              </div>
              <el-select
                v-else
                :model-value="getEditingValue(row, 'abnormality_category')"
                @update:model-value="(val: any) => setEditingValue(row, 'abnormality_category', val)"
                placeholder="选择异常类别"
                size="small"
                style="width: 100%"
                filterable
                allow-create
                clearable
              >
                <el-option
                  v-for="category in abnormalityCategories"
                  :key="category.category_name"
                  :label="category.category_name"
                  :value="category.category_name"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 异常描述 - 可编辑 -->
          <el-table-column prop="merged_descriptions" label="异常描述" min-width="300">
            <template #default="{ row }">
              <div v-if="!isRowEditing(row)" @dblclick="startEdit(row)">
                <el-tooltip :content="row.merged_descriptions || '无'" placement="top">
                  <div style="max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                    {{ row.merged_descriptions || '无' }}
                  </div>
                </el-tooltip>
              </div>
              <el-input
                v-else
                :model-value="getEditingValue(row, 'abnormality_description')"
                @update:model-value="(val: any) => setEditingValue(row, 'abnormality_description', val)"
                type="textarea"
                :rows="2"
                :placeholder="getEditingValue(row, 'abnormality_category') ? '输入异常描述' : '请先选择异常类别'"
                :disabled="!getEditingValue(row, 'abnormality_category')"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- 异常关闭 - 可编辑 -->
          <el-table-column prop="is_closed" label="异常关闭" min-width="120" align="center">
            <template #default="{ row }">
              <div v-if="!isRowEditing(row)" @dblclick="startEdit(row)">
                <template v-if="row.abnormality_category">
                  <el-tag :type="row.is_closed ? 'success' : 'warning'" size="small">
                    {{ row.is_closed ? '已关闭' : '未关闭' }}
                  </el-tag>
                </template>
                <span v-else>—</span>
              </div>
              <el-switch
                v-else
                :model-value="getEditingValue(row, 'abnormality_closed')"
                @update:model-value="(val: any) => setEditingValue(row, 'abnormality_closed', val)"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                :disabled="!getEditingValue(row, 'abnormality_category')"
                size="small"
              />
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" min-width="160" align="center" fixed="right">
            <template #default="{ row }">
              <div v-if="!isRowEditing(row)">
                <el-button
                  type="primary"
                  size="small"
                  @click="startEdit(row)"
                  :icon="Edit"
                >
                  编辑
                </el-button>
              </div>
              <div v-else class="edit-actions">
                <el-button
                  type="success"
                  size="small"
                  @click="saveEdit(row)"
                  :icon="Check"
                  :loading="saving"
                >
                  保存
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="cancelEdit(row)"
                  :icon="Close"
                >
                  取消
                </el-button>
              </div>
            </template>
          </el-table-column>
        </template>

        <!-- 异常汇总（周期）表列 -->
        <template v-else-if="reportType === 'abnormal_weekly'">
          <!-- 周粒度 -->
          <template v-if="weeklyGranularity === 'week'">
            <el-table-column prop="week" label="周数" min-width="80" align="center">
              <template #default="{ row }">
                第{{ row.week }}周
              </template>
            </el-table-column>
            <el-table-column prop="weekLabel" label="周范围" min-width="200" />
          </template>
          <!-- 月粒度 -->
          <template v-else-if="weeklyGranularity === 'month'">
            <el-table-column prop="period" label="月份" min-width="120" />
          </template>
          <!-- 年粒度 -->
          <template v-else>
            <el-table-column prop="period" label="年份" min-width="100" />
          </template>

          <el-table-column prop="abnormality_category" label="异常类别" min-width="140" />
          <el-table-column prop="occurrence_count" label="出现次数" min-width="100" align="right">
            <template #default="{ row }">
              <el-tag type="warning" size="small">
                {{ row.occurrence_count || 0 }}
              </el-tag>
            </template>
          </el-table-column>

        </template>

        <!-- PPH记录详情列（动态渲染） -->
        <template v-else>
          <!-- 动态渲染列 - 按照用户配置的字段顺序 -->
          <el-table-column
            v-for="column in orderedColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :min-width="column.minWidth"
            :align="column.align"
            :sortable="column.sortable"
          >
            <!-- 表头模板 - 包含筛选功能 -->
            <template #header="{ column: headerColumn }">
              <div class="custom-header">
                <span>{{ headerColumn.label }}</span>
                <el-popover placement="bottom" :width="getFilterWidth(column.prop)" trigger="click">
                  <template #reference>
                    <el-icon class="filter-icon" :class="{ active: columnFilters[column.prop] }">
                      <Filter />
                    </el-icon>
                  </template>
                  <div class="filter-content">
                    <!-- 日期筛选 -->
                    <el-date-picker
                      v-if="isDateField(column.prop)"
                      v-model="columnFilters[column.prop]"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      size="small"
                      @change="applyColumnFilter"
                    />
                    <!-- 选择筛选 -->
                    <el-select
                      v-else-if="isSelectField(column.prop)"
                      v-model="columnFilters[column.prop]"
                      placeholder="选择筛选条件"
                      clearable
                      multiple
                      size="small"
                      @change="applyColumnFilter"
                    >
                      <el-option
                        v-for="option in getSelectOptions(column.prop)"
                        :key="option"
                        :label="option"
                        :value="option"
                      />
                    </el-select>
                    <!-- 数值筛选 -->
                    <div v-else-if="isNumberField(column.prop)" class="number-filter">
                      <el-input-number
                        v-model="columnFilters[column.prop].min"
                        placeholder="最小值"
                        size="small"
                        :min="0"
                        @change="applyColumnFilter"
                      />
                      <span>至</span>
                      <el-input-number
                        v-model="columnFilters[column.prop].max"
                        placeholder="最大值"
                        size="small"
                        :min="0"
                        @change="applyColumnFilter"
                      />
                    </div>
                    <!-- 文本筛选 -->
                    <el-input
                      v-else
                      v-model="columnFilters[column.prop]"
                      placeholder="输入筛选条件"
                      clearable
                      size="small"
                      @input="applyColumnFilter"
                    />
                  </div>
                </el-popover>
              </div>
            </template>

            <!-- 单元格内容模板 -->
            <template #default="{ row }">
              <span v-if="column.prop === 'abnormality_closed'">
                <template v-if="row.abnormality_category">
                  <el-tag :type="row.abnormality_closed ? 'success' : 'warning'">
                    {{ row.abnormality_closed ? '已关闭' : '未关闭' }}
                  </el-tag>
                </template>
                <span v-else>—</span>
              </span>
              <span v-else-if="column.prop === 'is_standard_operating'">
                <el-tag :type="row.is_standard_operating ? 'success' : 'warning'">
                  {{ row.is_standard_operating ? '是' : '否' }}
                </el-tag>
              </span>
              <span v-else-if="column.prop === 'is_main_product'">
                <el-tag :type="getMainProductValue(row.is_main_product) ? 'success' : 'warning'">
                  {{ getMainProductValue(row.is_main_product) ? '是' : '否' }}
                </el-tag>
              </span>
              <span v-else-if="column.prop === 'is_whole_machine'">
                <el-tag :type="row.is_whole_machine ? 'primary' : 'info'">
                  {{ row.is_whole_machine ? '整机' : '整机+电机' }}
                </el-tag>
              </span>
              <span v-else-if="column.prop === 'efficiency_rate' && row.efficiency_rate !== null">
                {{ row.efficiency_rate.toFixed(1) }}%
              </span>
              <span v-else-if="column.prop === 'target_takt_time'">
                {{ row.is_whole_machine === 1
                    ? (row.target_takt_time || '-')
                    : '-'
                }}
              </span>
              <span v-else-if="column.prop === 'target_motor_takt_time'">
                {{ row.is_whole_machine === 0
                    ? (row.target_motor_takt_time || '-')
                    : '-'
                }}
              </span>
              <span v-else-if="isNumberField(column.prop) && row[column.prop] !== null">
                {{ formatNumber(row[column.prop], column.prop) }}
              </span>
              <span v-else>
                {{ row[column.prop] || '-' }}
              </span>
            </template>
          </el-table-column>
        </template>

        <!-- 操作列 -->
        <el-table-column v-if="reportType === 'detail'" label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              @click="viewDetails(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[20, 50, 100, 200]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadCurrentReportData"
          @current-change="loadCurrentReportData"
        />
      </div>
    </el-card>

    <!-- 字段配置对话框 -->
    <el-dialog
      v-model="fieldConfigVisible"
      title="配置显示字段"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="activeConfigTab" type="border-card">
        <!-- 字段选择标签页 -->
        <el-tab-pane label="字段选择" name="selection">
          <div class="field-config">
        <div class="field-group">
          <h4>基础信息</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="record_date">记录日期</el-checkbox>
            <el-checkbox label="target_record_date">目标记录日期</el-checkbox>
            <el-checkbox label="line_name">生产线名称</el-checkbox>
            <el-checkbox label="order_number">订单号</el-checkbox>
            <el-checkbox label="material_code">物料编码</el-checkbox>
            <el-checkbox label="product_name">产品名称</el-checkbox>
            <el-checkbox label="demand_category">需求分类</el-checkbox>
            <el-checkbox label="customer_number">顾客号</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>时间信息</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="start_time">开始时间</el-checkbox>
            <el-checkbox label="end_time">结束时间</el-checkbox>
            <el-checkbox label="abnormal_loss_minutes">异常损失时间</el-checkbox>
            <el-checkbox label="break_minutes">休息时间</el-checkbox>
            <el-checkbox label="changeover_minutes">转产时间</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>订单数量信息</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="order_quantity">订单数量</el-checkbox>
            <el-checkbox label="inbound_quantity">入库数量</el-checkbox>
            <el-checkbox label="completed_total_quantity">完成总数量</el-checkbox>
            <el-checkbox label="to_complete_quantity">待完成数量</el-checkbox>
            <el-checkbox label="quantity">完成数量</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>人员信息</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="total_people">总人数</el-checkbox>
            <el-checkbox label="working_people">线上人员</el-checkbox>
            <el-checkbox label="offline_staff">线外人员</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>PPH信息</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="calculated_pph">实际PPH</el-checkbox>
            <el-checkbox label="average_pph">PPH平均值</el-checkbox>
            <el-checkbox label="target_pph">目标PPH</el-checkbox>
            <el-checkbox label="estimate_pph">预估PPH</el-checkbox>
            <el-checkbox label="efficiency_rate">达成率</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>设备相关</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="belt_speed">皮带速度</el-checkbox>

          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>扩展计算字段</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="net_working_minutes">净工作时间(分钟)</el-checkbox>
            <el-checkbox label="actual_takt_seconds">实际节拍时间(秒)</el-checkbox>
            <el-checkbox label="target_takt_time">整机节拍</el-checkbox>
            <el-checkbox label="target_motor_takt_time">电机节拍</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>异常信息</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="abnormality_category">异常类别</el-checkbox>
            <el-checkbox label="abnormality_description">异常描述</el-checkbox>
            <el-checkbox label="abnormality_closed">异常关闭</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>标识字段</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="is_standard_operating">符合标准</el-checkbox>
            <el-checkbox label="is_main_product">主打产品</el-checkbox>
            <el-checkbox label="is_whole_machine">生产类型</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="field-group">
          <h4>系统管理</h4>
          <el-checkbox-group v-model="selectedFields">
            <el-checkbox label="created_at">创建时间</el-checkbox>
            <el-checkbox label="updated_at">更新时间</el-checkbox>
            <el-checkbox label="created_by">创建人</el-checkbox>
            <el-checkbox label="sync_status">同步状态</el-checkbox>
          </el-checkbox-group>
        </div>
          </div>
        </el-tab-pane>

        <!-- 字段排序标签页 -->
        <el-tab-pane label="字段排序" name="sorting">
          <div class="field-sorting">
            <div class="sorting-hint">
              <el-alert
                title="拖拽调整字段显示顺序"
                type="info"
                :closable="false"
                show-icon
              >
                <template #default>
                  拖拽下方的字段项目可以调整表格中字段的显示顺序。只有已选择的字段才会显示在列表中。
                </template>
              </el-alert>
            </div>

            <div class="sortable-field-list" ref="sortableContainer">
              <div
                v-for="field in visibleSortableFields"
                :key="field"
                :data-field="field"
                class="sortable-field-item"
              >
                <el-icon class="drag-handle"><Menu /></el-icon>
                <span class="field-label">{{ getFieldLabel(field) }}</span>
                <span class="field-name">{{ field }}</span>
              </div>
            </div>

            <div v-if="visibleSortableFields.length === 0" class="empty-sorting">
              <el-empty description="请先在字段选择页面选择要显示的字段" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="field-config-footer">
          <el-button @click="selectAllFields">全选</el-button>
          <el-button @click="selectDefaultFields">默认字段</el-button>
          <el-button @click="clearAllFields">清空</el-button>
          <el-button type="primary" @click="applyFieldConfig">应用</el-button>
          <el-button @click="fieldConfigVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Search, Refresh, Download, Filter, Menu, Edit, Check, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { useFormDataStore } from '@/stores/formDataStore'
import * as echarts from 'echarts'


// 定义组件名
defineOptions({
  name: 'ReportsPage'
})

import { pphService } from '../../services/pphService'

// 类型定义
interface ReportRecord {
  id?: number
  record_date: string
  line_name: string
  order_number: string
  material_code: string
  product_name: string
  quantity: number
  total_people: number
  calculated_pph: number
  target_pph?: number | null
  efficiency_rate?: number | null
  start_time?: string
  end_time?: string
}
interface LineItem { line_name: string }

// 表单数据持久化store
const effChartType = ref<'line'|'bar'>('line')

const formDataStore = useFormDataStore()

// 状态
const loading = ref(false)
const records = ref<ReportRecord[]>([])
const targets = ref<any[]>([])

// 达标率分析状态
// 维度=按生产线 时的多选/排行
const effSelectedLines = ref<string[] | null>(null) // null=全选
const effRankingMode = ref<'top'|'bottom'>('top')
const effRankingN = ref<number>(5)
// BottomN 默认 3（当切换到 bottom 时初次使用）
watch(effRankingMode, (m) => { if (m==='bottom' && effRankingN.value===5) effRankingN.value = 3 })
// 口径：达标率(阈值) | 平均达成率(无阈值)
const effMetric = ref<'pass_rate'|'avg_efficiency'>('pass_rate')


const effPreset = ref<'this_week'|'last_week'|'this_month'|'last_month'|'this_year'|'last_year'|'last_7_days'|'last_30_days'>('this_month')
const effGranularity = ref<'week'|'month'|'year'>('week')
const effDimension = ref<'overall'|'line'>('overall')
const effStartYear = ref(new Date().getFullYear())
const effEndYear = ref(new Date().getFullYear())
const effStartMonth = ref(1)
const effEndMonth = ref(12)
const effThreshold = ref<number>(95)
const effGranLabel = computed(() => effGranularity.value === 'week' ? '周' : (effGranularity.value === 'month' ? '月' : '年'))

function applyEffPreset() {
  const now = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  let start: string | null = null
  let end: string | null = null
  switch (effPreset.value) {
    case 'this_week': { const day=now.getDay(); const diff=day===0?6:day-1; const mon=new Date(now); mon.setDate(now.getDate()-diff); const sun=new Date(mon); sun.setDate(mon.getDate()+6); start=fmt(mon); end=fmt(sun); break }

    case 'last_week': { const day=now.getDay(); const diff=day===0?6:day-1; const thisMon=new Date(now); thisMon.setDate(now.getDate()-diff); const lastMon=new Date(thisMon); lastMon.setDate(thisMon.getDate()-7); const lastSun=new Date(lastMon); lastSun.setDate(lastSun.getDate()+6); start=fmt(lastMon); end=fmt(lastSun); break }
    case 'this_month': { const first=new Date(now.getFullYear(), now.getMonth(), 1); const last=new Date(now.getFullYear(), now.getMonth()+1, 0); start=fmt(first); end=fmt(last); break }
    case 'last_month': { const first=new Date(now.getFullYear(), now.getMonth()-1, 1); const last=new Date(now.getFullYear(), now.getMonth(), 0); start=fmt(first); end=fmt(last); break }
    case 'this_year': { start=`${now.getFullYear()}-01-01`; end=`${now.getFullYear()}-12-31`; break }
    case 'last_year': { const y=now.getFullYear()-1; start=`${y}-01-01`; end=`${y}-12-31`; break }
    case 'last_7_days': { const endD=new Date(now); const startD=new Date(now); startD.setDate(startD.getDate()-6); start=fmt(startD); end=fmt(endD); break }
    case 'last_30_days': { const endD=new Date(now); const startD=new Date(now); startD.setDate(startD.getDate()-29); start=fmt(startD); end=fmt(endD); break }
  }
  if (start && end) {
    effQueryRange.value = [start, end]
  }
}

const effQueryRange = ref<string[]|null>(null)
const effChartData = ref<any>({ data: [] })
const effStats = ref<any>({ total_groups:0, covered_groups:0, coverage:0, pass_records:0, pass_rate:0 })

async function loadEfficiencyAnalysis() {
  try {
    loading.value = true
    const params: any = {
      granularity: effGranularity.value,
      dimension: effDimension.value,
      threshold_percent: effThreshold.value
    }
    // 生产线多选与TopN/BottomN
    if (effDimension.value === 'line') {
      // 多选产线
      if (effSelectedLines.value && effSelectedLines.value.length) {
        params.line_names = effSelectedLines.value.join(',')
      }
      // 传 metric，便于后端决定榜单口径（前端切换时会再追加）
      params.metric = effMetric.value
      // TopN/BottomN 作为客户端筛选；如果后端未来要计算，也可以下发 rankingMode/N：
      params.ranking_mode = effRankingMode.value
      params.ranking_n = effRankingN.value
    }
    if (effQueryRange.value && effQueryRange.value.length===2) {
      params.start_date = effQueryRange.value[0]
      params.end_date = effQueryRange.value[1]
    } else {
      // 回退到年/月选择（非周粒度时）
      if (effGranularity.value !== 'week') {
        params.start_year = effStartYear.value
        params.end_year = effEndYear.value
        params.start_month = effStartMonth.value
        params.end_month = effEndMonth.value
      } else {
        // 周粒度且无 preset 范围，则用本周
        params.preset = 'this_week'
      }
    }

    const resp = await pphService.getEfficiencyAnalysis(params)
    effChartData.value = resp
    effStats.value = resp?.statistics || { total_groups:0, covered_groups:0, coverage:0, pass_records:0, pass_rate:0 }
  } catch (error) {
    console.error('加载达标率分析失败:', error)
    ElMessage.error('加载达标率分析失败')
  } finally {
    loading.value = false
  }
}

function resetEfficiencyFilters() {
  effPreset.value = 'this_month'
  effGranularity.value = 'week'
  effDimension.value = 'overall'
  const y = new Date().getFullYear()
  effStartYear.value = y
  effEndYear.value = y
  effStartMonth.value = 1
  effEndMonth.value = 12
  effThreshold.value = 95
  effQueryRange.value = null
  effChartData.value = { data: [] }
  effStats.value = { total_groups:0, covered_groups:0, coverage:0, pass_records:0, pass_rate:0 }
}

async function exportEfficiencyAnalysis() {
  try {
    if (!effChartData.value || !effChartData.value.data || !effChartData.value.data.length) {
      ElMessage.warning('没有数据可导出，请先查询')
      return
    }

    const apiUrl = pphService.getApiUrl()
    const params = new URLSearchParams()
    params.append('granularity', effGranularity.value)
    params.append('dimension', effDimension.value)
    params.append('metric', effMetric.value)
    if (effDimension.value === 'line') {
      if (effSelectedLines.value && effSelectedLines.value.length) {
        params.append('line_names', effSelectedLines.value.join(','))
      }
    }
    if (effQueryRange.value && effQueryRange.value.length === 2) {
      params.append('start_date', effQueryRange.value[0])
      params.append('end_date', effQueryRange.value[1])
    } else if (effGranularity.value !== 'week') {
      params.append('start_year', String(effStartYear.value))
      params.append('end_year', String(effEndYear.value))
      params.append('start_month', String(effStartMonth.value))
      params.append('end_month', String(effEndMonth.value))
    } else {
      params.append('preset', 'this_week')
    }
    if (effMetric.value === 'pass_rate') params.append('threshold_percent', String(effThreshold.value))

    const res = await fetch(`${apiUrl}/api/reports/efficiency-analysis/export?${params.toString()}`, { method: 'GET' })
    if (!res.ok) throw new Error(`导出失败: ${res.status}`)
    const blob = await res.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    const labelMetric = effMetric.value === 'avg_efficiency' ? '平均达成率' : '达标率'
    const fileLabel = effDimension.value === 'line' ? '按生产线' : '总体'
    const rangeLabel = (effQueryRange.value||[]).join('_') || `${effStartYear.value}-${String(effStartMonth.value).padStart(2,'0')}_${effEndYear.value}-${String(effEndMonth.value).padStart(2,'0')}`
    a.download = `达标率分析_${fileLabel}_${effGranularity.value}_${rangeLabel}_${labelMetric}.xlsx`
    document.body.appendChild(a)
    a.click()
    a.remove()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出任务已开始')
  } catch (error) {
    console.error('导出达标率分析失败:', error)
    ElMessage.error('导出失败')
  }
}
// 达标率分析表格数据
const effTableRows = computed(() => {
  const rows: any[] = []
  const data = effChartData.value?.data || []
  for (const p of data) {
    const items = p.data || []
    if (effDimension.value === 'line') {
      for (const it of items) {
        rows.push({
          period: p.period,
          line_name: it.line_name,
          total_groups: it.total_groups,
          covered_groups: it.covered_groups,
          coverage: it.coverage,
          pass_records: it.pass_records,
          pass_rate: it.pass_rate,
          avg_efficiency: it.avg_efficiency
        })
      }
    } else {
      const it = items[0] || {}
      rows.push({
        period: p.period,
        total_groups: it.total_groups,
        covered_groups: it.covered_groups,
        coverage: it.coverage,
        pass_records: it.pass_records,
        pass_rate: it.pass_rate,
        avg_efficiency: it.avg_efficiency
      })
    }
  }
  return rows
})

// 初始化/更新图表
let effChart: any = null

function renderEffChart() {
  const el = document.getElementById('eff-chart')
  if (!el) return
  if (!effChart) effChart = echarts.init(el)

  // 构造 X 轴与序列
  const periods: string[] = (effChartData.value?.data || []).map((p: any) => p.period)
  let series: any[] = []
  const metricKey = effMetric.value === 'avg_efficiency' ? 'avg_efficiency' : 'pass_rate'

  if (effDimension.value === 'line') {
    // 收集所有产线
    const linesSet = new Set<string>()
    for (const p of (effChartData.value?.data || [])) {
      for (const it of (p.data || [])) linesSet.add(it.line_name)
    }
    let linesArr = Array.from(linesSet)

    // 应用TopN/BottomN（基于所选口径在整体周期上的平均）
    if (effRankingMode.value && effRankingN.value > 0) {
      const avgByLine = new Map<string, number>()
      for (const ln of linesArr) {
        const vals = (effChartData.value?.data||[]).map((p:any)=> {
          const found = (p.data||[]).find((x:any)=>x.line_name===ln)
          return found ? Number(found[metricKey]||0) : 0
        })
        const avg = vals.length ? vals.reduce((s:number,v:number)=>s+v,0)/vals.length : 0
        avgByLine.set(ln, avg)
      }
      linesArr = linesArr.sort((a,b)=> (avgByLine.get(b)??0) - (avgByLine.get(a)??0))
      if (effRankingMode.value==='bottom') linesArr.reverse()
      linesArr = linesArr.slice(0, Math.min(effRankingN.value, 13))
    } else {
      linesArr = linesArr.slice(0, 13)
    }

    // 多选过滤（如用户明确选择，以用户选择为准）
    if (effSelectedLines.value && effSelectedLines.value.length) {
      linesArr = linesArr.filter(ln => effSelectedLines.value!.includes(ln))
    }

    series = linesArr.map((ln) => ({
      name: ln,
      type: effChartType.value,
      smooth: true,
      data: (effChartData.value?.data || []).map((p: any) => {
        const found = (p.data || []).find((x: any) => x.line_name === ln)
        return found ? (Number(found[metricKey]||0)) : 0
      })
    }))
  } else {
    series = [{
      name: effMetric.value==='avg_efficiency' ? '总体平均达成率' : '总体达标率',
      type: effChartType.value,
      smooth: true,
      data: (effChartData.value?.data || []).map((p: any) => {
        const it = (p.data || [])[0]
        return it ? (Number(it[metricKey]||0)) : 0
      })
    }]
  }

  const option: any = {
    tooltip: { trigger: 'axis', valueFormatter: (v: any)=> `${v}%` },
    legend: { type: 'scroll' },
    xAxis: { type: 'category', data: periods },
    yAxis: { type: 'value', min: 0, max: 100, axisLabel: { formatter: '{value}%' } },
    series
  }
  effChart.setOption(option as any, true)
}

watch([effChartData, effDimension, effMetric, effChartType, effSelectedLines, effRankingMode, effRankingN], () => {
  renderEffChart()
})

onMounted(() => {
  renderEffChart()
  window.addEventListener('resize', handleResize)
})

function handleResize() {
  if (effChart) effChart.resize()
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (effChart) { effChart.dispose(); effChart = null }
})


const lines = ref<LineItem[]>([])
const abnormalityCategories = ref<any[]>([])
const dateRange = ref<string[] | null>(null)

// 详情页快捷时间 preset
const detailPreset = ref<'this_week'|'last_week'|'this_month'|'last_month'|'this_year'|'last_year'|'last_7_days'|'last_30_days'>('this_month')

function applyDetailPreset() {
  const now = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`

  let start: string | null = null
  let end: string | null = null

  switch (detailPreset.value) {
    case 'this_week': {
      const day = now.getDay()
      const diffToMon = day === 0 ? 6 : day - 1
      const mon = new Date(now); mon.setDate(now.getDate() - diffToMon)
      const sun = new Date(mon); sun.setDate(mon.getDate() + 6)
      start = fmt(mon); end = fmt(sun); break
    }
    case 'last_week': {
      const day = now.getDay()
      const diffToMon = day === 0 ? 6 : day - 1
      const thisMon = new Date(now); thisMon.setDate(now.getDate() - diffToMon)
      const lastMon = new Date(thisMon); lastMon.setDate(thisMon.getDate() - 7)
      const lastSun = new Date(lastMon); lastSun.setDate(lastMon.getDate() + 6)
      start = fmt(lastMon); end = fmt(lastSun); break
    }
    case 'this_month': {
      const first = new Date(now.getFullYear(), now.getMonth(), 1)
      const last = new Date(now.getFullYear(), now.getMonth()+1, 0)
      start = fmt(first); end = fmt(last); break
    }
    case 'last_month': {
      const first = new Date(now.getFullYear(), now.getMonth()-1, 1)
      const last = new Date(now.getFullYear(), now.getMonth(), 0)
      start = fmt(first); end = fmt(last); break
    }
    case 'this_year': {
      start = `${now.getFullYear()}-01-01`
      end = `${now.getFullYear()}-12-31`; break
    }
    case 'last_year': {
      const y = now.getFullYear()-1
      start = `${y}-01-01`; end = `${y}-12-31`; break
    }
    case 'last_7_days': {
      const endD = new Date(now)
      const startD = new Date(now); startD.setDate(startD.getDate()-6)
      start = fmt(startD); end = fmt(endD); break
    }
    case 'last_30_days': {
      const endD = new Date(now)
      const startD = new Date(now); startD.setDate(startD.getDate()-29)
      start = fmt(startD); end = fmt(endD); break
    }
  }

  if (start && end) {
    dateRange.value = [start, end]
    filters.start_date = start
    filters.end_date = end
  }
}


// 报表类型 - 强制重置状态
const reportType = ref<'detail' | 'pph_summary' | 'abnormal_summary' | 'abnormal_weekly' | 'efficiency_analysis'>('detail')

// 强制清除状态函数
function forceResetState() {
  reportType.value = 'detail'
  console.log('强制重置reportType为:', reportType.value)
}

// 主打产品值判断函数 - 强制修复版本
function getMainProductValue(value: any): boolean {
  console.log('🔍 主打产品调试 - 原始值:', value, '类型:', typeof value)

  // 强制逻辑：只有明确的真值才返回true
  let result = false

  if (value === true || value === 1 || value === '1' || value === 'true') {
    result = true
  } else if (value === false || value === 0 || value === '0' || value === 'false' || value === null || value === undefined) {
    result = false
  } else {
    // 未知值默认为false
    console.warn('⚠️ 主打产品未知值:', value)
    result = false
  }

  console.log('✅ 主打产品最终判断结果:', result)
  return result
}
const pphSummaryData = ref<any[]>([])
const abnormalSummaryData = ref<any[]>([])
const abnormalWeeklyData = ref<any>({})

// 异常汇总（周期）相关状态
const weeklyPreset = ref<'this_week' | 'last_week' | 'this_month' | 'last_month' | 'this_year' | 'last_year'>('this_month')
const weeklyGranularity = ref<'week' | 'month' | 'year'>('month')

// 异常汇总快捷时间 preset
const abnormalSummaryPreset = ref<'this_week'|'last_week'|'this_month'|'last_month'|'this_year'|'last_year'|'last_7_days'|'last_30_days'>('this_month')
function applyAbnormalSummaryPreset() {
  const now = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  let start: string | null = null
  let end: string | null = null
  switch (abnormalSummaryPreset.value) {
    case 'this_week': { const day = now.getDay(); const diff = day===0?6:day-1; const mon=new Date(now); mon.setDate(now.getDate()-diff); const sun=new Date(mon); sun.setDate(mon.getDate()+6); start=fmt(mon); end=fmt(sun); break }
    case 'last_week': { const day = now.getDay(); const diff = day===0?6:day-1; const thisMon=new Date(now); thisMon.setDate(now.getDate()-diff); const lastMon=new Date(thisMon); lastMon.setDate(thisMon.getDate()-7); const lastSun=new Date(lastMon); lastSun.setDate(lastMon.getDate()+6); start=fmt(lastMon); end=fmt(lastSun); break }
    case 'this_month': { const first=new Date(now.getFullYear(), now.getMonth(), 1); const last=new Date(now.getFullYear(), now.getMonth()+1, 0); start=fmt(first); end=fmt(last); break }
    case 'last_month': { const first=new Date(now.getFullYear(), now.getMonth()-1, 1); const last=new Date(now.getFullYear(), now.getMonth(), 0); start=fmt(first); end=fmt(last); break }
    case 'this_year': { start=`${now.getFullYear()}-01-01`; end=`${now.getFullYear()}-12-31`; break }
    case 'last_year': { const y=now.getFullYear()-1; start=`${y}-01-01`; end=`${y}-12-31`; break }
    case 'last_7_days': { const endD=new Date(now); const startD=new Date(now); startD.setDate(startD.getDate()-6); start=fmt(startD); end=fmt(endD); break }
    case 'last_30_days': { const endD=new Date(now); const startD=new Date(now); startD.setDate(startD.getDate()-29); start=fmt(startD); end=fmt(endD); break }
  }
  if (start && end) {
    abnormalSummaryDateRange.value = [start, end]
  }
}

const weeklyStartYear = ref(new Date().getFullYear())
const weeklyEndYear = ref(new Date().getFullYear())
const weeklyStartMonth = ref(1)
const weeklyEndMonth = ref(12)
const weeklyLineName = ref('')
const weeklyAbnormalityCategory = ref('')

// PPH汇总快捷时间 preset
const pphSummaryPreset = ref<'this_week'|'last_week'|'this_month'|'last_month'|'this_year'|'last_year'|'last_7_days'|'last_30_days'>('this_month')
function applyPphSummaryPreset() {
  const now = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  let start: string | null = null
  let end: string | null = null
  switch (pphSummaryPreset.value) {
    case 'this_week': { const day = now.getDay(); const diff = day===0?6:day-1; const mon=new Date(now); mon.setDate(now.getDate()-diff); const sun=new Date(mon); sun.setDate(mon.getDate()+6); start=fmt(mon); end=fmt(sun); break }
    case 'last_week': { const day = now.getDay(); const diff = day===0?6:day-1; const thisMon=new Date(now); thisMon.setDate(now.getDate()-diff); const lastMon=new Date(thisMon); lastMon.setDate(thisMon.getDate()-7); const lastSun=new Date(lastMon); lastSun.setDate(lastMon.getDate()+6); start=fmt(lastMon); end=fmt(lastSun); break }
    case 'this_month': { const first=new Date(now.getFullYear(), now.getMonth(), 1); const last=new Date(now.getFullYear(), now.getMonth()+1, 0); start=fmt(first); end=fmt(last); break }
    case 'last_month': { const first=new Date(now.getFullYear(), now.getMonth()-1, 1); const last=new Date(now.getFullYear(), now.getMonth(), 0); start=fmt(first); end=fmt(last); break }
    case 'this_year': { start=`${now.getFullYear()}-01-01`; end=`${now.getFullYear()}-12-31`; break }
    case 'last_year': { const y=now.getFullYear()-1; start=`${y}-01-01`; end=`${y}-12-31`; break }
    case 'last_7_days': { const endD=new Date(now); const startD=new Date(now); startD.setDate(startD.getDate()-6); start=fmt(startD); end=fmt(endD); break }
    case 'last_30_days': { const endD=new Date(now); const startD=new Date(now); startD.setDate(startD.getDate()-29); start=fmt(startD); end=fmt(endD); break }
  }
  if (start && end) {
    pphSummaryDateRange.value = [start, end]
  }
}

const weeklyAbnormalityClosed = ref('')

// 粒度为 week 时隐藏 年/月 选择；month/year 时显示
const showYearMonthControls = computed(() => weeklyGranularity.value !== 'week')


// PPH汇总表筛选条件
const pphSummaryFilters = reactive({
  line_name: '', // 兼容旧参数
  line_names: [] as string[],
  order_number: '',
  material_code: '',
  product_name: ''
})
const pphSummaryDateRange = ref<string[] | null>(null)

// 异常汇总表筛选条件
const abnormalSummaryFilters = reactive({
  line_name: '',
  order_number: '',
  material_code: '',
  product_name: '',
  abnormality_category: '',
  abnormality_closed: ''
})
const abnormalSummaryDateRange = ref<string[] | null>(null)

// 异常汇总表编辑状态
const editingRows = ref(new Set<string>()) // 正在编辑的行ID集合
const editingData = ref<Record<string, any>>({}) // 编辑中的数据
const saving = ref(false) // 保存状态

// 字段配置相关状态
const fieldConfigVisible = ref(false)
const selectedFields = ref<string[]>([])
const activeConfigTab = ref('selection')
const sortableContainer = ref<HTMLElement>()  // 拖拽容器引用

// 筛选和排序相关状态
const tableRef = ref<any>()
const columnFilters = ref<Record<string, any>>({
  // 基础信息字段
  record_date: null,
  target_record_date: null,
  line_name: [],
  order_number: '',
  material_code: '',
  product_name: '',
  demand_category: '',
  customer_number: '',

  // 时间相关字段
  start_time: null,
  end_time: null,

  // 数量相关字段
  order_quantity: { min: null, max: null },
  inbound_quantity: { min: null, max: null },
  completed_total_quantity: { min: null, max: null },
  to_complete_quantity: { min: null, max: null },
  quantity: { min: null, max: null },
  defect_quantity: { min: null, max: null },
  rework_quantity: { min: null, max: null },
  scrap_quantity: { min: null, max: null },

  // 人员相关字段
  total_people: { min: null, max: null },
  working_people: { min: null, max: null },
  offline_staff: { min: null, max: null },
  online_staff: { min: null, max: null },

  // 时间损失相关字段
  abnormal_loss_minutes: { min: null, max: null },
  break_minutes: { min: null, max: null },
  changeover_minutes: { min: null, max: null },
  maintenance_time: { min: null, max: null },

  // PPH相关字段
  calculated_pph: { min: null, max: null },
  average_pph: { min: null, max: null },
  target_pph: { min: null, max: null },
  estimate_pph: { min: null, max: null },
  efficiency_rate: { min: null, max: null },

  // 其他字段
  belt_speed: { min: null, max: null },
  net_working_minutes: { min: null, max: null },
  actual_takt_seconds: { min: null, max: null },
  abnormality_category: '',
  abnormality_description: '',

  // 标识字段
  is_standard_operating: null,
  is_non_main_product: null,
  is_whole_machine: null,

  // 系统字段
  created_at: null,
  updated_at: null,
  created_by: '',
  sync_status: ''
})

const sortConfig = ref({
  prop: '',
  order: ''
})

// 🔧 修复BUG：移除未使用的columnOrder，字段排序统一在配置对话框中管理

// 🔧 优化3：根据用户需求设置默认字段（基于截图中勾选的字段）
const defaultFields = [
  // 基础信息（截图中勾选的字段）
  'record_date',           // ✅ 记录日期
  'target_record_date',    // ✅ 目标记录日期
  'line_name',            // ✅ 生产线名称
  'order_number',         // ✅ 订单号
  'material_code',        // ✅ 物料编码
  'product_name',         // ✅ 产品名称

  // 时间信息（截图中勾选的字段）
  'start_time',           // ✅ 开始时间
  'end_time',             // ✅ 结束时间
  'abnormal_loss_minutes', // ✅ 异常损失时间(分钟) - 修正字段名
  'break_minutes',        // ✅ 休息时间(分钟) - 修正字段名
  'changeover_minutes',   // ✅ 转产时间(分钟) - 修正字段名

  // 订单数量信息（截图中勾选的字段）
  'quantity',             // ✅ 完成数量

  // 人员信息（截图中勾选的字段）
  'total_people',         // ✅ 总人数
  'working_people',       // ✅ 线上人员
  'offline_staff',        // ✅ 线外人员

  // PPH信息（截图中勾选的字段）
  'calculated_pph',       // ✅ 实际PPH
  'average_pph',          // ✅ 平均PPH
  'target_pph',           // ✅ 目标PPH
  'estimate_pph',         // ✅ 预估PPH
  'efficiency_rate',      // ✅ 达成率

  // 设备相关（截图中勾选的字段）
  'belt_speed',           // ✅ 皮带速度

  // 扩展计算字段（截图中勾选的字段）
  'net_working_minutes',  // ✅ 净工作时间(分钟)
  'actual_takt_seconds',  // ✅ 实际节拍时间(秒) — 按需默认显示
  'target_takt_time',     // ✅ 整机节拍
  'target_motor_takt_time', // ✅ 电机节拍

  // 异常信息（截图中勾选的字段）
  'abnormality_category', // ✅ 异常类别
  'abnormality_description', // ✅ 异常描述
  'abnormality_closed',   // ✅ 异常关闭

  // 标识字段（截图中勾选的字段）
  'is_main_product',      // ✅ 主打产品
  'is_whole_machine'      // ✅ 生产类型
]

// 所有可用字段 - 基于数据库表的完整字段列表（统一字段标准）
const allFields = [
  // 基础信息字段
  'record_date',           // 记录日期
  'target_record_date',    // 目标记录日期
  'line_name',            // 生产线名称
  'order_number',         // 订单号
  'material_code',        // 物料编码
  'product_name',         // 产品名称
  'demand_category',      // 需求分类
  'customer_number',      // 顾客号

  // 时间相关字段
  'start_time',           // 开始时间
  'end_time',            // 结束时间

  // 订单数量字段
  'order_quantity',       // 订单数量
  'inbound_quantity',     // 入库数量
  'completed_total_quantity', // 完成总数量
  'to_complete_quantity', // 待完成数量
  'quantity',            // 完成数量

  // 人员字段（统一字段标准）
  'total_people',        // 总人数
  'working_people',      // 线上人员
  'offline_staff',       // 线外人员

  // 时间损失字段
  'abnormal_loss_minutes', // 异常损失时间(分钟)
  'break_minutes',       // 休息时间(分钟)
  'changeover_minutes',  // 换线时间(分钟)

  // 设备相关字段
  'belt_speed',          // 皮带速度

  // PPH计算字段
  'calculated_pph',      // 实际PPH值
  'average_pph',         // 平均PPH值
  'target_pph',         // 目标PPH值
  'estimate_pph',       // 预估PPH值
  'efficiency_rate',    // 效率达成率

  // 扩展计算字段
  'net_working_minutes', // 净工作时间(分钟)
  'actual_takt_seconds', // 实际节拍时间(秒)
  'target_takt_time',    // 节拍
  'target_motor_takt_time', // 整机节拍

  // 异常信息字段
  'abnormality_category',    // 异常类别
  'abnormality_description', // 异常描述
  'abnormality_closed',      // 异常关闭

  // 标识字段
  'is_standard_operating',  // 是否标准作业
  'is_main_product',       // 是否主打产品 ✅ 修复：添加缺失的字段
  'is_whole_machine',      // 是否整机

  // 系统管理字段
  'created_at',            // 创建时间
  'updated_at',           // 更新时间
  'created_by',           // 创建人
  'sync_status'           // 同步状态
]

// 计算可见字段
const visibleFields = computed(() => {
  const result: { [key: string]: boolean } = {}
  allFields.forEach(field => {
    result[field] = selectedFields.value.includes(field)
  })
  return result
})

// 可排序的字段列表（只包含已选择的字段）
const visibleSortableFields = computed(() => {
  return selectedFields.value.filter(field => allFields.includes(field))
})

// 字段标签映射
const fieldLabels: Record<string, string> = {
  'record_date': '记录日期',
  'target_record_date': '目标记录日期',
  'line_name': '生产线名称',
  'order_number': '订单号',
  'material_code': '物料编码',
  'product_name': '产品名称',
  'demand_category': '需求分类',
  'customer_number': '顾客号',
  'start_time': '开始时间',
  'end_time': '结束时间',
  'abnormal_loss_minutes': '异常损失时间',
  'break_minutes': '休息时间',
  'changeover_minutes': '转产时间',
  'order_quantity': '订单数量',
  'inbound_quantity': '入库数量',
  'completed_total_quantity': '累计完成数量',
  'to_complete_quantity': '待完成数量',
  'quantity': '完成数量',
  'defect_quantity': '不良品数量',
  'rework_quantity': '返工数量',
  'scrap_quantity': '报废数量',
  'total_people': '总人数',
  'working_people': '线上人员',
  'offline_staff': '线外人员',
  'belt_speed': '皮带速度',
  'calculated_pph': '实际PPH',
  'average_pph': 'PPH平均值',
  'target_pph': '目标PPH',
  'estimate_pph': '预估PPH',
  'efficiency_rate': '效率达成率',
  'net_working_minutes': '净工作时间',
  'actual_takt_seconds': '实际节拍时间',
  'target_takt_time': '整机节拍',
  'target_motor_takt_time': '电机节拍',
  'abnormality_category': '异常类别',
  'abnormality_closed': '异常关闭',
  'abnormality_description': '异常描述',
  'downtime_reason': '停机原因',
  'is_standard_operating': '标准作业',
  'is_non_main_product': '非主打产品',
  'is_main_product': '主打产品',
  'is_whole_machine': '整机生产',
  'created_at': '创建时间',
  'updated_at': '更新时间',
  'created_by': '创建人',
  'sync_status': '同步状态'
}

// 获取字段标签
function getFieldLabel(field: string): string {
  return fieldLabels[field] || field
}

// 获取列配置
function getColumnConfig(fieldName: string) {
  const baseConfig = {
    prop: fieldName,
    label: getFieldLabel(fieldName),
    sortable: 'custom',
    minWidth: 120
  }

  // 特殊字段的配置
  const specialConfigs: Record<string, any> = {
    record_date: { minWidth: 140 },
    target_record_date: { minWidth: 140 },
    line_name: { minWidth: 120 },
    order_number: { minWidth: 180 },
    material_code: { minWidth: 150 },
    product_name: { minWidth: 300 },
    abnormality_description: { minWidth: 180 },
    quantity: { align: 'right' },
    total_people: { align: 'right' },
    working_people: { align: 'right' },
    offline_staff: { align: 'right' },
    calculated_pph: { align: 'right' },
    target_pph: { align: 'right' },
    estimate_pph: { align: 'right' },
    efficiency_rate: { align: 'right' },
    abnormal_loss_minutes: { align: 'right', minWidth: 140 },
    break_minutes: { align: 'right', minWidth: 140 },
    changeover_minutes: { align: 'right', minWidth: 140 },
    net_working_minutes: { align: 'right', minWidth: 140 },
    actual_takt_seconds: { align: 'right' },
    belt_speed: { align: 'right' },
    abnormality_closed: { align: 'center' },
    is_standard_operating: { align: 'center' },
    is_main_product: { align: 'center' },
    is_whole_machine: { align: 'center' },
    created_at: { minWidth: 160 },
    updated_at: { minWidth: 160 }
  }

  return {
    ...baseConfig,
    ...specialConfigs[fieldName]
  }
}

// 动态列配置 - 根据字段顺序渲染表格列
const orderedColumns = computed(() => {
  return selectedFields.value.map(fieldName => {
    const config = getColumnConfig(fieldName)
    return {
      ...config,
      visible: visibleFields.value[fieldName] || false
    }
  }).filter(col => col.visible)
})

// 辅助函数：判断字段类型
function isDateField(fieldName: string): boolean {
  return ['record_date', 'target_record_date', 'start_time', 'end_time', 'created_at', 'updated_at'].includes(fieldName)
}

function isSelectField(fieldName: string): boolean {
  return ['line_name', 'abnormality_category', 'downtime_reason'].includes(fieldName)
}

function isNumberField(fieldName: string): boolean {
  return [
    'quantity', 'total_people', 'working_people', 'offline_staff',
    'calculated_pph', 'target_pph', 'estimate_pph', 'efficiency_rate',
    'abnormal_loss_minutes', 'break_minutes', 'changeover_minutes',
    'net_working_minutes', 'actual_takt_seconds', 'belt_speed',
    'order_quantity', 'inbound_quantity', 'to_complete_quantity'
  ].includes(fieldName)
}

function getFilterWidth(fieldName: string): number {
  if (isDateField(fieldName)) return 300
  if (isNumberField(fieldName)) return 250
  return 200
}

function getSelectOptions(fieldName: string): string[] {
  return uniqueValues.value[fieldName] || []
}

function formatNumber(value: any, fieldName: string): string {
  if (value === null || value === undefined) return '-'

  const num = parseFloat(value)
  if (isNaN(num)) return '-'

  // PPH相关字段保留1位小数
  if (['calculated_pph', 'target_pph', 'estimate_pph','average_pph'].includes(fieldName)) {
    return num.toFixed(2)
  }

  // 时间相关字段显示整数
  if (['abnormal_loss_minutes', 'break_minutes', 'changeover_minutes', 'net_working_minutes'].includes(fieldName)) {
    return Math.round(num).toString()
  }

  // 实际节拍字段统一保留2位小数
  if (fieldName === 'actual_takt_seconds') {
    return num.toFixed(2)
  }

  // 其他数值字段
  return num.toString()
}

// 获取表格标题
function getTableTitle(): string {
  switch (reportType.value) {
    case 'pph_summary':
      return 'PPH汇总表'
    case 'abnormal_summary':
      return '异常汇总表'
    case 'abnormal_weekly':
      return `异常汇总（${weeklyGranularity.value === 'week' ? '周' : weeklyGranularity.value === 'month' ? '月' : '年'}）`
    default:
      return 'PPH记录详情'
  }
}

// 获取年份选项（当前年份前后3年）
function getYearOptions(): number[] {
  const currentYear = new Date().getFullYear()
  const years: number[] = []
  for (let i = currentYear - 3; i <= currentYear + 1; i++) {
    years.push(i)
  }
  return years
}

// 获取唯一值用于筛选选项
const uniqueValues = computed(() => {
  const values: Record<string, string[]> = {
    line_name: [],
    order_number: [],
    material_code: [],
    product_name: []
  }

  records.value.forEach(record => {
    Object.keys(values).forEach(key => {
      const value = record[key as keyof ReportRecord]
      if (value && !values[key].includes(String(value))) {
        values[key].push(String(value))
      }
    })
  })

  // 排序唯一值
  Object.keys(values).forEach(key => {
    values[key].sort()
  })

  return values
})

// 获取当前表格数据
const getCurrentTableData = computed(() => {
  switch (reportType.value) {
    case 'pph_summary':
      return pphSummaryData.value
    case 'abnormal_summary':
      return abnormalSummaryData.value
    case 'abnormal_weekly': {
      // 异常汇总（周期）扁平化用于表格显示（周/月/年）
      const periods = abnormalWeeklyData.value?.data || []
      const flatData: any[] = []
      periods.forEach((p: any) => {
        p.data.forEach((item: any) => {
          flatData.push({
            ...item,
            period: p.period,
            periodLabel: p.periodLabel,
            week: p.week,
            weekLabel: p.weekLabel,
            startDate: p.startDate,
            endDate: p.endDate
          })
        })
      })
      pagination.total = flatData.length
      const start = (pagination.page - 1) * pagination.limit
      return flatData.slice(start, start + pagination.limit)
    }
    default:
      return filteredAndSortedRecords.value
  }
})

// 筛选和排序后的数据
const filteredAndSortedRecords = computed(() => {
  let filtered = [...records.value]

  // 应用列筛选
  Object.keys(columnFilters.value).forEach(key => {
    const filter = columnFilters.value[key]

    // 检查筛选条件是否有效
    if ((key === 'record_date' || key === 'target_record_date' || key === 'created_at' || key === 'updated_at') && filter && Array.isArray(filter) && filter.length === 2) {
      filtered = filtered.filter(record => {
        const recordValue = record[key as keyof ReportRecord] as unknown as string | number | null | undefined
        if (recordValue == null) return false
        return (recordValue as any) >= filter[0] && (recordValue as any) <= filter[1]
      })
    } else if (key === 'line_name' && Array.isArray(filter) && filter.length > 0) {
      filtered = filtered.filter(record => filter.includes(record.line_name))
    } else if (typeof filter === 'string' && filter.trim()) {
      filtered = filtered.filter(record => {
        const value = record[key as keyof ReportRecord]
        return String(value || '').toLowerCase().includes(filter.toLowerCase())
      })
    } else if (filter && typeof filter === 'object' && 'min' in filter && 'max' in filter && (filter.min !== null || filter.max !== null)) {
      filtered = filtered.filter(record => {
        const value = Number(record[key as keyof ReportRecord]) || 0
        const min = filter.min !== null ? filter.min : -Infinity
        const max = filter.max !== null ? filter.max : Infinity
        return value >= min && value <= max
      })
    } else if (typeof filter === 'boolean' || filter === true || filter === false) {
      filtered = filtered.filter(record => {
        const value = record[key as keyof ReportRecord]
        return value === filter
      })
    }
  })

  // 应用排序
  if (sortConfig.value.prop && sortConfig.value.order) {
    filtered.sort((a, b) => {
      const prop = sortConfig.value.prop as keyof ReportRecord
      const aVal = a[prop] || 0
      const bVal = b[prop] || 0

      if (sortConfig.value.order === 'ascending') {
        return aVal > bVal ? 1 : -1
      } else {
        return aVal < bVal ? 1 : -1
      }
    })
  }

  return filtered
})

// 表单和筛选
const filters = reactive({
  line_name: '',
  order_number: '',
  material_code: '',
  product_name: '',
  efficiency_operator: '',
  efficiency_value: undefined as number | undefined,
  start_date: '',
  end_date: '',
  date: '',
  // 多选支持：从 URL 解析后写入
  line_names: [] as string[],
  material_codes: [] as string[]
})

// URL 参数解析：支持多选 line_names/material_codes（逗号分隔或重复参数）
function parseUrlMulti(name: string): string[] {
  const params = new URLSearchParams(window.location.search)
  const list = params.getAll(name)
  const combined = list.join(',')
  return combined
    .split(',')
    .map(s => s.trim())
    .filter(s => s.length > 0)
}

function initFiltersFromUrl() {
  const params = new URLSearchParams(window.location.search)
  filters.start_date = params.get('start_date') || ''
  filters.end_date = params.get('end_date') || ''
  filters.line_name = params.get('line_name') || ''
  filters.order_number = params.get('order_number') || ''
  filters.material_code = params.get('material_code') || ''
  filters.product_name = params.get('product_name') || ''
  filters.efficiency_operator = params.get('efficiency_operator') || ''
  const ev = params.get('efficiency_value')
  filters.efficiency_value = ev ? Number(ev) : undefined
  // 多选
  filters.line_names = parseUrlMulti('line_names')
  filters.material_codes = parseUrlMulti('material_codes')
}

const pagination = reactive({
  page: 1,
  limit: 50,
  total: 0
})

// 统计数据 - 根据报表类型动态使用字段
// detail/pph_summary 使用 PPH 统计字段；abnormal_* 使用异常统计字段
const statistics = ref<any>({
  // PPH 统计
  totalRecords: 0,
  averagePPH: 0,
  averageEfficiency: 0,
  achievementRate: 0,
  // 异常统计
  totalAbnormalRecords: 0,
  abnormalCategoriesCount: 0,
  closedCount: 0,
  unclosedCount: 0
})

// 表单验证规则（现在暂时不需要，但保留以备将来使用）
// const targetRules = {
//   material_code: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
//   line_name: [{ required: true, message: '请选择生产线', trigger: 'change' }],
//   product_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
//   record_date: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
//   takt_time: [{ required: true, type: 'number', min: 0.1, message: '节拍必须大于0', trigger: 'change' }],
//   standard_staff: [{ required: true, type: 'number', min: 1, message: '标准人数必须大于0', trigger: 'change' }]
// }

// 方法
async function loadLines() {
  try {
    const response = await pphService.getLines()
    // 兼容 { lines: [...] } 或直接数组返回
    lines.value = (response && Array.isArray(response.lines)) ? response.lines : (response?.lines || response || [])
  } catch (error: any) {
    console.error('获取生产线列表失败:', error)
    ElMessage.error('获取生产线列表失败')
  }
}

async function loadAbnormalityCategories() {
  try {
    const response = await pphService.getAbnormalityCategories()
    abnormalityCategories.value = response.categories || []
  } catch (error: any) {
    console.error('获取异常类别列表失败:', error)
    ElMessage.error('获取异常类别列表失败')
  }
}

async function loadReportData() {
  try {
    loading.value = true
    const params = {
      ...filters,
      page: pagination.page,
      limit: pagination.limit
    }

    console.log('🔍 查询参数:', params)
    console.log('🔍 日期范围:', { start_date: params.start_date, end_date: params.end_date })

    const response = await pphService.getPPHRecords(params)
    // 后端返回 { success, data, pagination, statistics }
    const outer: any = response || {}
    records.value = outer.data || outer.records || []
    pagination.total = outer.pagination?.total ?? outer.total ?? 0

    // 使用后端返回的统计数据
    if (outer.statistics) {
      console.log('📊 收到后端统计数据:', outer.statistics)
      statistics.value = outer.statistics
      console.log('📊 设置前端统计数据:', statistics.value)
    } else {
      console.warn('⚠️ 后端未返回统计数据')
    }

  } catch (error: any) {
    console.error('获取报表数据失败:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

async function refreshTargets() {
  try {
    // 抓取目标值列表用于后续分析（本页未直接展示）
    const resp = await pphService.getTargets({ line_name: filters.line_name || undefined })
    targets.value = Array.isArray(resp) ? resp : (resp?.targets || [])
  } catch (error: any) {
    console.error('刷新目标值失败:', error)
    ElMessage.error('刷新目标值失败')
  }
}

function handleDateRangeChange(dates: string[]) {
  if (dates && dates.length === 2) {
    filters.start_date = dates[0]
    filters.end_date = dates[1]
  } else {
    filters.start_date = ''
    filters.end_date = ''
  }
}

// 报表类型切换处理
function handleReportTypeChange(type: 'detail' | 'pph_summary' | 'abnormal_summary' | 'abnormal_weekly' | 'efficiency_analysis') {
  reportType.value = type
  // 🚀 性能优化：切换报表类型时不自动加载数据，避免不必要的API调用
  // 用户需要点击"查询"按钮来加载数据，这样可以：
  // 1. 减少服务器压力
  // 2. 避免页面卡顿
  // 3. 让用户先设置查询条件再加载
  console.log(`📊 切换到报表类型: ${type}，等待用户点击查询按钮`)
}

// 根据当前报表类型加载对应的数据
function loadCurrentReportData() {
  switch (reportType.value) {
    case 'pph_summary':
      loadPPHSummaryData()
      break
    case 'abnormal_summary':
      loadAbnormalSummaryData()
      break
    case 'abnormal_weekly':
      loadAbnormalWeeklyData()
      break
    default:
      loadReportData()
      break
  }
}

// 加载PPH汇总数据
async function loadPPHSummaryData() {
  try {
    loading.value = true
    const params: any = {}

    // 添加日期范围
    if (pphSummaryDateRange.value && pphSummaryDateRange.value.length === 2) {
      params.start_date = pphSummaryDateRange.value[0]
      params.end_date = pphSummaryDateRange.value[1]
    }

    // 添加筛选条件（支持多选产线）
    if (pphSummaryFilters.line_names && pphSummaryFilters.line_names.length) {
      params.line_names = pphSummaryFilters.line_names.join(',')
    } else if (pphSummaryFilters.line_name) {
      params.line_name = pphSummaryFilters.line_name
    }
    if (pphSummaryFilters.order_number) params.order_number = pphSummaryFilters.order_number
    if (pphSummaryFilters.material_code) params.material_code = pphSummaryFilters.material_code
    if (pphSummaryFilters.product_name) params.product_name = pphSummaryFilters.product_name



    // 分页参数
    params.page = pagination.page
    params.limit = pagination.limit

    const response = await pphService.getPPHSummary(params)
    pphSummaryData.value = response?.data || []

    // 使用后端返回的统计数据
    if (response?.statistics) {
      console.log('📊 PPH汇总收到后端统计数据:', response.statistics)
      statistics.value = response.statistics
      console.log('📊 PPH汇总设置前端统计数据:', statistics.value)
    } else {
      console.warn('⚠️ PPH汇总后端未返回统计数据')
    }

    // 正确设置分页
    if (response?.pagination) {
      pagination.total = response.pagination.total || 0
      pagination.page = response.pagination.page || pagination.page
      pagination.limit = response.pagination.limit || pagination.limit
    }
  } catch (error: any) {
    console.error('获取PPH汇总数据失败:', error)
    ElMessage.error('获取PPH汇总数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置PPH汇总筛选条件
function resetPPHSummaryFilters() {
  pphSummaryFilters.line_name = ''
  pphSummaryFilters.line_names = []
  pphSummaryFilters.order_number = ''
  pphSummaryFilters.material_code = ''
  pphSummaryFilters.product_name = ''
  pphSummaryDateRange.value = null
  pphSummaryData.value = []
  ElMessage.success('PPH汇总筛选条件已重置')
}

// 导出PPH汇总报表
async function exportPPHSummaryReport() {
  try {
    ElMessage.info('正在导出PPH汇总报表，请稍候...')

    const data = pphSummaryData.value
    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可以导出，请先查询数据')
      return
    }

    // 构建导出参数
    const exportParams = new URLSearchParams()
    if (pphSummaryDateRange.value && pphSummaryDateRange.value.length === 2) {
      exportParams.append('start_date', pphSummaryDateRange.value[0])
      exportParams.append('end_date', pphSummaryDateRange.value[1])
    }
    if (pphSummaryFilters.line_names && pphSummaryFilters.line_names.length) {
      exportParams.append('line_names', pphSummaryFilters.line_names.join(','))
    } else if (pphSummaryFilters.line_name) {
      exportParams.append('line_name', pphSummaryFilters.line_name)
    }
    exportParams.append('format', 'excel')

    // 发起导出请求
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/reports/pph-summary/export?${exportParams}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }
    })

    if (!response.ok) {
      throw new Error(`导出失败: ${response.status}`)
    }

    // 获取文件名并下载
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = 'PPH汇总报表.xlsx'
    if (contentDisposition) {
      const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (match && match[1]) {
        filename = match[1].replace(/['"]/g, '')
      }
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)

    ElMessage.success('PPH汇总报表导出成功')
  } catch (error: any) {
    console.error('导出PPH汇总报表失败:', error)
    ElMessage.error(`导出失败: ${error?.message || '未知错误'}`)
  }
}

// 加载异常汇总数据
async function loadAbnormalSummaryData() {
  try {
    loading.value = true
    const params: any = {}

    // 添加日期范围
    if (abnormalSummaryDateRange.value && abnormalSummaryDateRange.value.length === 2) {
      params.start_date = abnormalSummaryDateRange.value[0]
      params.end_date = abnormalSummaryDateRange.value[1]
    }

    // 添加筛选条件
    if (abnormalSummaryFilters.line_name) params.line_name = abnormalSummaryFilters.line_name
    if (abnormalSummaryFilters.order_number) params.order_number = abnormalSummaryFilters.order_number
    if (abnormalSummaryFilters.material_code) params.material_code = abnormalSummaryFilters.material_code
    if (abnormalSummaryFilters.product_name) params.product_name = abnormalSummaryFilters.product_name
    if (abnormalSummaryFilters.abnormality_category) params.abnormality_category = abnormalSummaryFilters.abnormality_category
    if (abnormalSummaryFilters.abnormality_closed !== '') params.abnormality_closed = abnormalSummaryFilters.abnormality_closed

    // 分页参数
    params.page = pagination.page
    params.limit = pagination.limit

    const response = await pphService.getAbnormalSummary(params)
    abnormalSummaryData.value = response?.data || []

    // 使用后端返回的统计数据（异常）
    if (response?.statistics) {
      statistics.value = {
        ...statistics.value,
        totalAbnormalRecords: response.statistics.totalAbnormalRecords || 0,
        abnormalCategoriesCount: response.statistics.abnormalCategoriesCount || 0,
        closedCount: response.statistics.closedCount || 0,
        unclosedCount: response.statistics.unclosedCount || 0
      }
    }

    // 正确设置分页
    if (response?.pagination) {
      pagination.total = response.pagination.total || 0
      pagination.page = response.pagination.page || pagination.page
      pagination.limit = response.pagination.limit || pagination.limit
    }
  } catch (error: any) {
    console.error('获取异常汇总数据失败:', error)
    ElMessage.error('获取异常汇总数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 重置异常汇总筛选条件
function resetAbnormalSummaryFilters() {
  abnormalSummaryFilters.line_name = ''
  abnormalSummaryFilters.order_number = ''
  abnormalSummaryFilters.material_code = ''
  abnormalSummaryFilters.product_name = ''
  abnormalSummaryFilters.abnormality_category = ''
  abnormalSummaryFilters.abnormality_closed = ''
  abnormalSummaryDateRange.value = null
  abnormalSummaryData.value = []
  ElMessage.success('异常汇总筛选条件已重置')
}

// ==================== 异常汇总表编辑功能 ====================

// 生成行的唯一标识
function getRowId(row: any): string {
  return `${row.record_date}_${row.line_name}_${row.order_number}_${row.material_code}_${row.product_name}_${row.abnormality_category}`
}

// 检查行是否正在编辑
function isRowEditing(row: any): boolean {
  return editingRows.value.has(getRowId(row))
}

// 获取编辑中的值
function getEditingValue(row: any, field: string): any {
  const rowId = getRowId(row)
  const editData = editingData.value[rowId]
  if (editData && editData.hasOwnProperty(field)) {
    return editData[field]
  }

  // 返回原始值
  if (field === 'abnormality_category') {
    return row.abnormality_category
  } else if (field === 'abnormality_description') {
    return row.merged_descriptions
  } else if (field === 'abnormality_closed') {
    return row.is_closed ? 1 : 0
  }
  return row[field]
}

// 设置编辑中的值
function setEditingValue(row: any, field: string, value: any): void {
  const rowId = getRowId(row)
  if (!editingData.value[rowId]) {
    editingData.value[rowId] = {}
  }
  editingData.value[rowId][field] = value
}

// 开始编辑
function startEdit(row: any): void {
  const rowId = getRowId(row)
  editingRows.value.add(rowId)

  // 初始化编辑数据
  editingData.value[rowId] = {
    abnormality_category: row.abnormality_category,
    abnormality_description: row.merged_descriptions,
    abnormality_closed: row.is_closed ? 1 : 0
  }

  console.log('🖊️ 开始编辑行:', rowId)
}

// 取消编辑
function cancelEdit(row: any): void {
  const rowId = getRowId(row)
  editingRows.value.delete(rowId)
  delete editingData.value[rowId]
  console.log('❌ 取消编辑行:', rowId)
}

// 保存编辑
async function saveEdit(row: any): Promise<void> {
  const rowId = getRowId(row)
  const editData = editingData.value[rowId]

  if (!editData) {
    ElMessage.error('没有编辑数据')
    return
  }

  try {
    saving.value = true

    // 业务校验：类别与描述必须成对出现
    const cat = editData.abnormality_category
    const desc = editData.abnormality_description

    const catEmpty = (cat === undefined || cat === null || cat === '')
    const descEmpty = (desc === undefined || desc === null || String(desc).trim() === '')

    if ((catEmpty && !descEmpty) || (!catEmpty && descEmpty)) {
      ElMessage.error('异常类别与异常描述需同时填写或同时为空')
      return
    }

    // 构建更新数据
    const updateData = {
      groupKey: {
        record_date: row.record_date,
        line_name: row.line_name,
        order_number: row.order_number,
        material_code: row.material_code,
        product_name: row.product_name,
        abnormality_category: row.abnormality_category ?? null
      },
      newValues: {
        abnormality_category: catEmpty ? null : cat,
        abnormality_description: descEmpty ? null : desc,
        abnormality_closed: catEmpty ? null : editData.abnormality_closed
      }
    }

    console.log('💾 保存编辑数据:', updateData)

    // 调用API（使用绝对地址，避免静态服务302重定向导致跨机失败）
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/records/abnormal-summary/batch`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        updates: [updateData]
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const result = await response.json()

    if (result.success) {
      // 更新本地数据
      row.abnormality_category = catEmpty ? null : cat
      row.merged_descriptions = descEmpty ? null : desc
      row.is_closed = catEmpty ? null : (editData.abnormality_closed === 1)

      // 退出编辑模式
      editingRows.value.delete(rowId)
      delete editingData.value[rowId]

      ElMessage.success(`保存成功，影响 ${result.summary?.totalAffectedRows || 0} 条记录`)
      console.log('✅ 保存成功:', result)
    } else {
      throw new Error(result.error || '保存失败')
    }

  } catch (error: any) {
    console.error('❌ 保存编辑失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

// 导出异常汇总报表
async function exportAbnormalSummaryReport() {
  try {
    ElMessage.info('正在导出异常汇总报表，请稍候...')

    const data = abnormalSummaryData.value
    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可以导出，请先查询数据')
      return
    }

    // 构建导出参数
    const exportParams = new URLSearchParams()
    if (abnormalSummaryDateRange.value && abnormalSummaryDateRange.value.length === 2) {
      exportParams.append('start_date', abnormalSummaryDateRange.value[0])
      exportParams.append('end_date', abnormalSummaryDateRange.value[1])
    }
    if (abnormalSummaryFilters.line_name) exportParams.append('line_name', abnormalSummaryFilters.line_name)
    if (abnormalSummaryFilters.order_number) exportParams.append('order_number', abnormalSummaryFilters.order_number)
    if (abnormalSummaryFilters.material_code) exportParams.append('material_code', abnormalSummaryFilters.material_code)
    if (abnormalSummaryFilters.product_name) exportParams.append('product_name', abnormalSummaryFilters.product_name)
    if (abnormalSummaryFilters.abnormality_category) exportParams.append('abnormality_category', abnormalSummaryFilters.abnormality_category)
    if (abnormalSummaryFilters.abnormality_closed) exportParams.append('abnormality_closed', abnormalSummaryFilters.abnormality_closed)
    exportParams.append('format', 'excel')

    // 发起导出请求
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/reports/abnormal-summary/export?${exportParams}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }
    })

    if (!response.ok) {
      throw new Error(`导出失败: ${response.status}`)
    }

    // 获取文件名并下载
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = '异常汇总报表.xlsx'
    if (contentDisposition) {
      const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (match && match[1]) {
        filename = match[1].replace(/['"]/g, '')
      }
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)

    ElMessage.success('异常汇总报表导出成功')
  } catch (error: any) {
    console.error('导出异常汇总报表失败:', error)
    ElMessage.error(`导出失败: ${error?.message || '未知错误'}`)
  }
}

// 加载异常汇总（周）数据
async function loadAbnormalWeeklyData() {
  try {
    loading.value = true
    const params: any = {
      start_year: weeklyStartYear.value,
      end_year: weeklyEndYear.value,
      start_month: weeklyStartMonth.value,
      end_month: weeklyEndMonth.value,
      // 周期汇总不区分生产线，后端已忽略该过滤
      abnormality_category: weeklyAbnormalityCategory.value || undefined,
      abnormality_closed: weeklyAbnormalityClosed.value || undefined,
      preset: weeklyPreset.value,
      granularity: weeklyGranularity.value,
    }

    // 调用异常汇总（周）API
    const response = await pphService.getAbnormalWeeklySummary(params)
    abnormalWeeklyData.value = response || {}

    // 使用后端返回的统计数据（异常-周）
    if (response?.statistics) {
      statistics.value = {
        ...statistics.value,
        totalAbnormalRecords: response.statistics.totalAbnormalRecords || 0,
        abnormalCategoriesCount: response.statistics.abnormalCategoriesCount || 0,
        closedCount: response.statistics.closedCount || 0,
        unclosedCount: response.statistics.unclosedCount || 0
      }
    }

    // 周视图采用前端分页，保留用户当前分页状态
    // 这里不重置 pagination，避免翻页后被强制回到第一页
  } catch (error: any) {
    console.error('获取异常周汇总数据失败:', error)
    ElMessage.error('获取异常周汇总数据失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}



// 重置异常汇总（周）筛选条件
function resetWeeklyFilters() {
  const currentYear = new Date().getFullYear()
  weeklyPreset.value = 'this_month'
  weeklyGranularity.value = 'month'
  weeklyStartYear.value = currentYear
  weeklyEndYear.value = currentYear
  weeklyStartMonth.value = 1
  weeklyEndMonth.value = 12
  weeklyLineName.value = ''
  weeklyAbnormalityCategory.value = ''
  weeklyAbnormalityClosed.value = ''
  abnormalWeeklyData.value = {}
  ElMessage.success('筛选条件已重置')
}

// 导出异常汇总（周）报表 - 调用后端Excel导出API
async function exportWeeklyReport() {
  try {
    ElMessage.info('正在导出异常汇总（周）报表，请稍候...')

    const data = getCurrentTableData.value
    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可以导出，请先查询数据')
      return
    }

    console.log(`📊 准备导出 ${data.length} 条异常汇总（周）数据`)

    // 构建导出数据
    const exportData = data.map((row: any) => ({
      '周数': `第${row.week}周`,
      '日期': row.record_date,
      '异常类别': row.abnormality_category,
      '发生次数': row.occurrence_count,
      '关闭次数': row.closed_count,
      '关闭率(%)': row.close_rate
    }))

    // 调用后端Excel导出API
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/excel/export/abnormal-weekly`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      },
      body: JSON.stringify({ data: exportData })
    })

    if (!response.ok) {
      const error = await response.json().catch(() => ({}))
      throw new Error(error.error || `导出失败: ${response.status}`)
    }

    // 获取文件名并下载
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = `异常汇总${weeklyGranularity.value === 'week' ? '周' : weeklyGranularity.value === 'month' ? '月' : '年'}报表_${new Date().toISOString().split('T')[0]}.xlsx`
    if (contentDisposition) {
      const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (match && match[1]) {
        filename = match[1].replace(/['"]/g, '')
      }
    }

    // 下载文件
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success(`Excel导出成功: ${filename}`)
  } catch (error: any) {
    console.error('导出异常汇总（周）报表失败:', error)
    ElMessage.error(`导出失败: ${error?.message || '未知错误'}`)
  }
}

function resetFilters() {
  // 重置所有筛选条件
  filters.line_name = ''
  filters.order_number = ''
  filters.material_code = ''
  filters.product_name = ''
  filters.efficiency_operator = ''
  filters.efficiency_value = undefined
  filters.start_date = ''
  filters.end_date = ''
  filters.date = ''

  // 重置日期范围选择器
  dateRange.value = []

  // 重置列筛选
  columnFilters.value = {
    // 基础信息字段
    record_date: null,
    target_record_date: null,
    line_name: [],
    order_number: '',
    material_code: '',
    product_name: '',
    product_series: '',
    demand_category: '',
    customer_number: '',

    // 时间相关字段
    start_time: null,
    end_time: null,

    // 数量相关字段
    order_quantity: { min: null, max: null },
    inbound_quantity: { min: null, max: null },
    completed_total_quantity: { min: null, max: null },
    to_complete_quantity: { min: null, max: null },
    quantity: { min: null, max: null },
    defect_quantity: { min: null, max: null },
    rework_quantity: { min: null, max: null },
    scrap_quantity: { min: null, max: null },

    // 人员相关字段
    total_people: { min: null, max: null },
    working_people: { min: null, max: null },
    offline_staff: { min: null, max: null },
    online_staff: { min: null, max: null },

    // 时间损失相关字段
    abnormal_loss_minutes: { min: null, max: null },
    break_minutes: { min: null, max: null },
    changeover_minutes: { min: null, max: null },
    maintenance_minutes: { min: null, max: null },

    // PPH相关字段
    calculated_pph: { min: null, max: null },
    target_pph: { min: null, max: null },
    estimate_pph: { min: null, max: null },
    efficiency_rate: { min: null, max: null },

    // 其他字段
    belt_speed: { min: null, max: null },
    net_working_minutes: { min: null, max: null },
    actual_takt_seconds: { min: null, max: null },
    abnormality_category: '',
    abnormality_description: '',

    // 标识字段
    is_standard_operating: null,
    is_non_main_product: null,
    is_whole_machine: null,

    // 系统字段
    created_at: null,
    updated_at: null,
    created_by: '',
    sync_status: ''
  }

  // 重置排序
  sortConfig.value = { prop: '', order: '' }

  // 重新加载数据
  loadReportData()

  ElMessage.success('筛选条件已重置')
}

// 列筛选处理
function applyColumnFilter() {
  // 筛选会通过计算属性自动应用
  console.log('应用列筛选:', columnFilters.value)
}

// 排序处理
function handleSortChange({ prop, order }: { prop: string; order: string }) {
  sortConfig.value = { prop, order }
  console.log('排序变更:', { prop, order })
}

// 禁用表格列头拖拽功能 - 修复BUG：防止字段名和列位置不匹配
function initColumnDrag() {
  // 🚫 禁用表格列头拖拽，避免与字段配置冲突
  // 用户应该在"配置显示字段"对话框中的"字段排序"标签页进行列排序
  console.log('⚠️ 表格列头拖拽已禁用，请使用字段配置对话框进行排序')
}

function viewDetails(row: any) {
  const baseline = row.target_pph || row.estimate_pph || null
  let baselineFrom = '无'


  if (row.target_pph) {
    baselineFrom = '目标'
  } else if (row.estimate_pph) {
    baselineFrom = '预估'
  }

  let effText = '—'
  if (baseline) {
    if (row.efficiency_rate) {
      effText = row.efficiency_rate.toFixed(1) + '%'
    } else {
      effText = '未计算'
    }
  }

  // 构建详细的字段显示
  const detailsHtml = `
    <div style="text-align: left; font-family: monospace; white-space: pre-line;">
<strong>📋 基本信息</strong>
记录ID: ${row.id}
记录日期: ${row.record_date}
生产线: ${row.line_name}
订单号: ${row.order_number}
物料编码: ${row.material_code || '-'}
产品名称: ${row.product_name || '-'}
产品系列: ${row.product_series || '-'}
顾客号: ${row.customer_number || '-'}
需求分类: ${row.demand_category || '-'}

<strong>⏰ 时间信息</strong>
开始时间: ${row.start_time}
结束时间: ${row.end_time}
净工作时间: ${row.net_working_minutes || '-'} 分钟
实际节拍: ${row.actual_takt_seconds ? row.actual_takt_seconds.toFixed(2) + ' 秒/件' : '-'}

<strong>📊 数量信息</strong>
完成数量: ${row.quantity}
订单数量: ${row.order_quantity || '-'}
入库数量: ${row.inbound_quantity || '-'}
累计完成: ${row.completed_total_quantity || '-'}
待完成: ${row.to_complete_quantity || '-'}
不良品: ${row.defect_quantity || 0}
返工: ${row.rework_quantity || 0}
报废: ${row.scrap_quantity || 0}

<strong>👥 人员信息</strong>
总人数: ${row.total_people}
线上人员: ${row.online_staff || row.working_people || '-'}
线外人员: ${row.offline_staff || 0}

<strong>⏱️ 时间损失</strong>
异常损失: ${row.abnormal_loss_minutes || 0} 分钟
小休时间: ${row.break_minutes || 0} 分钟
转产时间: ${row.changeover_minutes || 0} 分钟
维护时间: ${row.maintenance_minutes || 0} 分钟

<strong>📈 PPH指标</strong>
实际PPH: ${row.calculated_pph}
目标PPH: ${row.target_pph || '-'}
预估PPH: ${row.estimate_pph || '-'}
效率达成率: ${effText}
基线来源: ${baselineFrom}

<strong>🏭 生产特征</strong>
标准作业: ${(row.is_standard_operating === 1 || row.is_standard_operating === '1') ? '是' : '否'}
主打产品: ${getMainProductValue(row.is_main_product) ? '是' : '否'}
整机生产: ${(row.is_whole_machine === 1 || row.is_whole_machine === '1') ? '是' : '否'}

<strong>⏱️ 节拍信息</strong>
生产类型: ${(row.is_whole_machine === 1 || row.is_whole_machine === '1') ? '整机生产' : '电机生产'}
整机节拍: ${row.target_takt_time || '-'} 秒
电机节拍: ${row.target_motor_takt_time || '-'} 秒
当前适用: ${(row.is_whole_machine === 1 || row.is_whole_machine === '1') ? (row.target_takt_time || '-') : (row.target_motor_takt_time || '-')} 秒

<strong>🔧 其他信息</strong>
皮带拉速度: ${row.belt_speed || '-'} 秒/格
异常类别: ${row.abnormality_category || '-'}
异常描述: ${row.abnormality_description || '-'}
异常关闭: ${row.abnormality_category ? (row.abnormality_closed ? '已关闭' : '未关闭') : '-'}
停机原因: ${row.downtime_reason || '-'}
目标记录日期: ${row.target_record_date || '-'}

<strong>📝 系统信息</strong>
创建时间: ${row.created_at || '-'}
更新时间: ${row.updated_at || '-'}
创建人: ${row.created_by || '-'}
同步状态: ${row.sync_status || '-'}
    </div>
  `;

  ElMessageBox.alert(detailsHtml, '记录详情', {
    confirmButtonText: '确定',
    dangerouslyUseHTMLString: true,
    customStyle: { width: '600px' }
  })
}

async function exportReport() {
  try {
    ElMessage.info('正在导出报表，请稍候...')

    // 构建导出参数，包含当前查询条件
    const exportParams = new URLSearchParams()

    // 添加查询条件
    if (filters.start_date) exportParams.append('start_date', filters.start_date)
    if (filters.end_date) exportParams.append('end_date', filters.end_date)
    if (filters.line_name) exportParams.append('line_name', filters.line_name)
    if (filters.order_number) exportParams.append('order_number', filters.order_number)
    if (filters.material_code) exportParams.append('material_code', filters.material_code)
    if (filters.product_name) exportParams.append('product_name', filters.product_name)
    if (filters.efficiency_operator && filters.efficiency_value !== null && filters.efficiency_value !== undefined) {
      exportParams.append('efficiency_operator', filters.efficiency_operator)
      exportParams.append('efficiency_value', filters.efficiency_value.toString())
    }
    // 多选条件联动导出
    if (filters.line_names && filters.line_names.length) exportParams.append('line_names', filters.line_names.join(','))
    if (filters.material_codes && filters.material_codes.length) exportParams.append('material_codes', filters.material_codes.join(','))

    // 添加字段配置
    const visibleFields = selectedFields.value.length > 0 ? selectedFields.value.join(',') : defaultFields.join(',')
    exportParams.append('fields', visibleFields)

    // 添加导出格式
    exportParams.append('format', 'excel')

    // 发起导出请求 - 使用网络自适应地址
    const apiUrl = pphService.getApiUrl()
    const response = await fetch(`${apiUrl}/api/records/export?${exportParams}`, {
      method: 'GET',
      headers: {
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }
    })

    if (!response.ok) {
      throw new Error(`导出失败: ${response.status}`)
    }

    // 获取文件名
    const contentDisposition = response.headers.get('Content-Disposition')
    let filename = 'PPH报表.xlsx'
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch) {
        filename = filenameMatch[1].replace(/['"]/g, '')
      }
    }

    // 下载文件
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = filename
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)

    ElMessage.success('报表导出成功！')

  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error(`导出失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 字段配置相关方法
function showFieldConfig() {
  fieldConfigVisible.value = true
  // 初始化拖拽排序
  nextTick(() => {
    initSortable()
  })
}

function selectAllFields() {
  selectedFields.value = [...allFields]
}

function selectDefaultFields() {
  selectedFields.value = [...defaultFields]
}

function clearAllFields() {
  selectedFields.value = []
}

function applyFieldConfig() {
  // 🔧 修复BUG：正确同步字段配置和排序

  // 1. 保存可见字段配置
  localStorage.setItem('pph-reports-visible-fields', JSON.stringify(selectedFields.value))

  // 2. 保存字段排序（使用selectedFields的顺序）
  localStorage.setItem('pph-reports-field-order', JSON.stringify(selectedFields.value))

  // 3. 立即应用到当前页面
  // 重新计算可见字段对象，确保字段顺序正确
  const newVisibleFields: Record<string, boolean> = {}
  selectedFields.value.forEach(field => {
    newVisibleFields[field] = true
  })

  // 4. 更新响应式状态
  Object.keys(visibleFields.value).forEach(key => {
    visibleFields.value[key] = false
  })
  selectedFields.value.forEach(field => {
    visibleFields.value[field] = true
  })

  fieldConfigVisible.value = false
  ElMessage.success('字段配置已保存并应用')

  console.log('✅ 字段配置已更新:', {
    selectedFields: selectedFields.value,
    visibleFields: visibleFields.value
  })
}

// 初始化拖拽排序
function initSortable() {
  if (!sortableContainer.value) return

  Sortable.create(sortableContainer.value, {
    animation: 150,
    handle: '.drag-handle',
    onEnd: (evt: any) => {
      const oldIndex = evt.oldIndex!
      const newIndex = evt.newIndex!

      // 更新字段顺序
      const newOrder = [...selectedFields.value]
      const [movedItem] = newOrder.splice(oldIndex, 1)
      newOrder.splice(newIndex, 0, movedItem)

      selectedFields.value = newOrder
      ElMessage.success('字段顺序已更新')
    }
  })
}

function loadFieldConfig() {
  // 从本地存储加载字段配置
  const saved = localStorage.getItem('pph-reports-visible-fields')
  const savedOrder = localStorage.getItem('pph-reports-field-order')

  if (saved) {
    try {
      const fields = JSON.parse(saved)
      // 如果有保存的排序，使用排序后的字段列表
      if (savedOrder) {
        try {
          const orderedFields = JSON.parse(savedOrder)
          // 确保排序后的字段都在选中字段中
          selectedFields.value = orderedFields.filter((field: any) => fields.includes(field))
          // 添加任何新的选中字段（可能是新增的）
          fields.forEach((field: any) => {
            if (!selectedFields.value.includes(field)) {
              selectedFields.value.push(field)
            }
          })
        } catch {
          selectedFields.value = fields
        }
      } else {
        selectedFields.value = fields
      }
    } catch {
      selectedFields.value = [...defaultFields]
    }
  } else {
    selectedFields.value = [...defaultFields]
  }
}

// 保存报表筛选条件和字段配置
function saveReportsState() {
  const stateData = {
    filters: { ...filters },
    columnFilters: columnFilters.value,
    selectedFields: selectedFields.value,
    dateRange: dateRange.value,
    pagination: {
      page: pagination.page,
      limit: pagination.limit
    }
  }

  formDataStore.saveSearchForm('reports', stateData)
  formDataStore.savePageState('reports', {
    currentPage: pagination.page,
    pageSize: pagination.limit,
    selectedFields: selectedFields.value,
    fieldOrder: selectedFields.value,
    lastSearchParams: stateData
  })
}

// 恢复报表筛选条件和字段配置
function restoreReportsState() {
  const savedState = formDataStore.getSearchForm('reports')
  if (savedState && Object.keys(savedState).length > 0) {
    // 恢复基本筛选条件
    if (savedState.filters) {
      Object.assign(filters, savedState.filters)
    }

    // 恢复列筛选条件
    if (savedState.columnFilters) {
      Object.assign(columnFilters.value, savedState.columnFilters)
    }

    // 恢复字段配置
    if (savedState.selectedFields && Array.isArray(savedState.selectedFields)) {
      selectedFields.value = [...savedState.selectedFields]
    }

    // 恢复日期范围
    if (savedState.dateRange) {
      dateRange.value = savedState.dateRange
    }

    // 恢复分页
    if (savedState.pagination) {
      pagination.page = savedState.pagination.page || 1
      pagination.limit = savedState.pagination.limit || 50
    }

    // 检查是否有有效的搜索条件
    const hasValidFilters = savedState.filters && Object.keys(savedState.filters).some(key => {
      const value = savedState.filters[key]
      return value !== '' && value !== null && value !== undefined &&
             !(Array.isArray(value) && value.length === 0)
    })

    const hasValidColumnFilters = savedState.columnFilters && Object.keys(savedState.columnFilters).some(key => {
      const value = savedState.columnFilters[key]
      // 检查对象类型的值（如 min/max 范围）
      if (value && typeof value === 'object' && !Array.isArray(value)) {
        return Object.values(value).some(v => v !== null && v !== undefined && v !== '')
      }
      // 检查数组类型的值
      if (Array.isArray(value)) {
        return value.length > 0
      }
      // 检查基本类型的值
      return value !== '' && value !== null && value !== undefined
    })

    const hasValidDateRange = savedState.dateRange && savedState.dateRange.length > 0

    // 只有在有有效搜索条件时才自动执行查询
    if (hasValidFilters || hasValidColumnFilters || hasValidDateRange) {
      ElMessage.success('已恢复上次的筛选条件和字段配置')

      // 自动执行搜索 - 根据当前报表类型加载对应数据
      nextTick(() => {
        loadCurrentReportData()
      })
    } else {
      console.log('📊 恢复了字段配置，但没有有效的搜索条件，等待用户输入查询条件进行数据分析')
      // 只恢复字段配置，不自动查询
    }
  }
}

// 监听状态变化，自动保存
let saveStateTimer: number | null = null
function debouncedSaveState() {
  if (saveStateTimer) {
    clearTimeout(saveStateTimer)
  }
  saveStateTimer = setTimeout(() => {
    saveReportsState()
  }, 2000) // 2秒防抖
}

// 监听关键状态变化
watch(() => filters, debouncedSaveState, { deep: true })
watch(() => columnFilters.value, debouncedSaveState, { deep: true })
watch(() => selectedFields.value, debouncedSaveState, { deep: true })
watch(() => dateRange.value, debouncedSaveState)
watch(() => pagination.page, debouncedSaveState)
watch(() => pagination.limit, debouncedSaveState)

// 生命周期
onMounted(async () => {
  // 强制重置状态
  forceResetState()
  // 加载字段配置
  loadFieldConfig()

  // 先加载基础数据
  await Promise.all([
    loadLines(),
    loadAbnormalityCategories(),
    refreshTargets()
  ])

  // 尝试恢复状态（优先级高于URL参数）
  const savedState = formDataStore.getSearchForm('reports')
  const hasValidState = savedState && (
    (savedState.filters && Object.keys(savedState.filters).some(key => savedState.filters[key])) ||
    (savedState.columnFilters && Object.keys(savedState.columnFilters).some(key => savedState.columnFilters[key])) ||
    (savedState.selectedFields && savedState.selectedFields.length > 0) ||
    (savedState.dateRange && savedState.dateRange.length > 0)
  )

  if (hasValidState) {
    console.log('🔄 恢复报表页面保存的状态:', savedState)
    restoreReportsState()
  } else {
    console.log('📝 没有保存的状态，从URL初始化')
    // 没有保存的状态时，从URL初始化
    initFiltersFromUrl()

    // 智能加载策略：检查URL参数是否包含有效的查询条件
    const hasUrlFilters = filters.start_date || filters.end_date || filters.line_name ||
                         filters.order_number || filters.material_code || filters.product_name ||
                         filters.efficiency_operator || filters.efficiency_value !== undefined ||
                         filters.line_names?.length > 0 || filters.material_codes?.length > 0

    if (hasUrlFilters) {
      console.log('🔍 检测到URL查询参数，自动加载数据')
      loadCurrentReportData()
    } else {
      console.log('📊 报表分析页面已加载，等待用户输入查询条件进行数据分析')
      // 不自动加载数据，保持空状态，提升性能
    }
  }

  // 初始化列拖拽功能
  initColumnDrag()
})
</script>

<style scoped>
/* ✅ 页面容器和头部样式已移至公共样式 common.css */

.filter-card {
  margin-bottom: 20px;
}

/* 搜索容器样式 */
.search-container {
  max-width: 100%;
  overflow: hidden;
  padding-right: 16px;
}

.search-form {
  width: 100%;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 12px;
}

.form-row .el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}

.form-row-with-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.form-fields {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  flex: 1;
}

.form-fields .el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  flex-shrink: 0;
  margin-left: 16px;
}

.action-btn {
  width: 80px;
  flex-shrink: 0;
}

/* 表格筛选样式 */
.custom-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.filter-icon {
  margin-left: 4px;
  cursor: pointer;
  color: #909399;
  transition: color 0.3s;
}

.filter-icon:hover {
  color: #409eff;
}

.filter-icon.active {
  color: #409eff;
}

.filter-content {
  padding: 8px 0;
}

.number-filter {
  display: flex;
  align-items: center;
  gap: 8px;
}

.number-filter span {
  color: #606266;
  font-size: 12px;
}

/* 拖拽样式 */
.sortable-ghost {
  opacity: 0.4;
  background: #f0f9ff;
}

.sortable-chosen {
  background: #e1f5fe;
}

.sortable-drag {
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 表头拖拽提示 */
.el-table__header th {
  cursor: move;
  user-select: none;
}

.el-table__header th:hover {
  background-color: #f5f7fa;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.stat-card :deep(.el-statistic__head) {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 12px;
  letter-spacing: 0.5px;
}

.stat-card :deep(.el-statistic__content) {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
}

.stat-card :deep(.el-statistic__suffix) {
  font-size: 18px;
  font-weight: 500;
  margin-left: 6px;
  color: #909399;
}

.data-table {
  margin-bottom: 20px;
}

.data-table :deep(.el-table__header-wrapper) {
  background-color: #f8f9fa;
}

.data-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #303133;
  font-weight: 600;
  font-size: 14px;
  padding: 16px 8px;
}

.data-table :deep(.el-table__body tr) {
  transition: background-color 0.2s ease;
}

.data-table :deep(.el-table__body tr:hover) {
  background-color: #f0f9ff !important;
}

.data-table :deep(.el-table__body td) {
  font-size: 13px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

/* 字段配置相关样式 */
.field-config {
  max-height: 500px;
  overflow-y: auto;
}

.field-group {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: #fafafa;
}

.field-group h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
}

.field-group .el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.field-group .el-checkbox {
  margin-right: 0;
  width: 120px;
}

.field-config-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 字段排序样式 */
.field-sorting {
  padding: 20px;
}

.sorting-hint {
  margin-bottom: 20px;
}

.sortable-field-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: #fafafa;
}

.sortable-field-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e0e0e0;
  background-color: white;
  cursor: move;
  transition: all 0.2s ease;
}

.sortable-field-item:last-child {
  border-bottom: none;
}

.sortable-field-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sortable-field-item.sortable-ghost {
  opacity: 0.5;
  background-color: #409eff;
  color: white;
}

.drag-handle {
  margin-right: 12px;
  color: #909399;
  cursor: grab;
}

.drag-handle:active {
  cursor: grabbing;
}

.field-label {
  font-weight: 500;
  color: #303133;
  min-width: 120px;
}

.field-name {
  color: #909399;
  font-size: 12px;
  margin-left: auto;
}

.empty-sorting {
  padding: 40px;
  text-align: center;
}

/* 异常汇总表编辑样式 */
.edit-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.edit-actions .el-button {
  padding: 6px 12px;
  font-size: 13px;
  min-width: 60px;
  border-radius: 4px;
}

/* 双击编辑提示 */
.el-table .cell {
  cursor: pointer;
}

.el-table .cell:hover {
  background-color: rgba(64, 158, 255, 0.05);
}
</style>
